/*!
 *
 * Copyright (c) 2021-2024 Diality Inc. - All Rights Reserved.
 * \copyright
 * THIS CODE MAY NOT BE COPIED OR REPRODUCED IN ANY FORM, IN PART OR IN
 * WHOLE, WITHOUT THE EXPLICIT PERMISSION OF THE COPYRIGHT OWNER.
 *
 * \file    SettingsStack.qml
 * \author  (last)      Dara Navaei
 * \date    (last)      06-Mar-2024
 * \author  (original)  Behrouz NematiPour
 * \date    (original)  16-Apr-2021
 *
 */

// Qt
import QtQuick                  2.12

// Project
import Gui.Actions 0.1

//  Qml imports
import "qrc:/"
import "qrc:/globals"
import "qrc:/components"
import "qrc:/compounds"
import "qrc:/pages"

/*!
 * \brief   SettingsStack is the screen
 * which contains the main stack for all the Settings screens
 * This is the screen which will show up when "Settings" option
 * is selected from the main menu.
 */
StackItem { id : _root
    objectName: "_SettingsStack"

    stackView.initialItem   : _settingsHome

    property bool   serviceMode : false

    readonly property bool normalMode                   : ! ( _GuiView.manufactSetup ||   _GuiView.updateSetup ||   _GuiView.registerSetup )
    readonly property bool  setupMode                   :     _GuiView.manufactSetup ||   _GuiView.updateSetup ||   _GuiView.registerSetup
    readonly property bool onlyManufacturing            :     _GuiView.manufactMode  && ! _GuiView.updateMode  || ! _GuiView.registerMode   // <...>Mode is true if the POST passes
    readonly property bool onlyUpdating                 : !   _GuiView.manufactMode  &&   _GuiView.updateMode  || ! _GuiView.registerMode   // <...>Mode is true if the POST passes
    readonly property bool onlyRegistration             : !   _GuiView.manufactMode  && ! _GuiView.updateMode  ||   _GuiView.registerMode   // <...>Mode is true if the POST passes
    readonly property bool loggedIn                     :   serviceMode


    readonly property bool visibleLanguage              :   false
    readonly property bool visibleSWUpdate              :   false
    readonly property bool visibleDGScheduling          :   false
    readonly property bool visibleCalibration           :   false

    readonly property bool visibleInformation           :   true
    readonly property bool visibleVolumeBrightness      : ! onlyUpdating // same as service password, on application execution in updating, on mount files will be moved.
    readonly property bool visibleWiFi                  :   true
    readonly property bool visibleBluetooth             :   true
    readonly property bool visibleExportLogs            :   true

    //                                                  during the update we cannot enable the servce menu since the current set password is in ~denali folder
    //                                                  not the ~root which is the working folder during update.
    //TODO                                              in case is required we need to copy from denali to root for the update and copy back again,
    //                                                  if works it is a better approach better.
    readonly property bool visibleServicePassword       : ( normalMode          && ! loggedIn ) // || ( onlyUpdating &&    ! loggedIn )
    readonly property bool visibleDGCleaning            :   normalMode
    readonly property bool visibleRoInput               :   normalMode
    readonly property bool visibleRootSSHAccess         :                            loggedIn
    readonly property bool visibleFactoryReset          :                            loggedIn
    readonly property bool visibleDecommission          :                            loggedIn
    readonly property bool visibleSetDateTime           :                            loggedIn   ||   onlyUpdating
    readonly property bool visibleDeviceConfiguration   :   onlyManufacturing   &&   loggedIn
    readonly property bool visibleDeviceRegistration    :   onlyManufacturing   &&   loggedIn   ||   onlyRegistration
    readonly property bool visibleInstitutionalRecord   :   true


    enum ItemsIndex {
        Information         ,
        VolumeBrightness    ,
        WiFi                ,
        Bluetooth           ,
        DGCleaning          ,
        DGScheduling        ,
        ServicePassword     ,
        SetDateTime         ,
        ExportLogs          ,
        Language            ,
        RoInput             ,
        Calibration         ,
        DeviceConfiguration ,
        DeviceRegistration  ,
        SWUpdate            ,
        RootSSHAccess       ,
        FactoryReset        ,
        Decommission        ,
        InstitutionalRecord
    }
    property var itemsText  : [
        qsTr("Information"                  ), // Information
        qsTr("Volume And Brightness"        ), // VolumeBrightness
        qsTr("Wi-Fi"                        ), // WiFi
        qsTr("Bluetooth Cuff"               ), // Bluetooth
        qsTr("DG Cleaning"                  ), // DGCleaning
        qsTr("DG Scheduling"                ), // DGScheduling
        qsTr("Service"                      ), // servicePassword
        qsTr("Set Date And Time"            ), // SetDateTime
        qsTr("Export Logs"                  ), // ExportLogs
        qsTr("Set Language"                 ), // Language
        qsTr("Water Input Mode"             ), // RoInput
        qsTr("Calibration"                  ), // Calibration
        qsTr("Device Configuration"         ), // Device Configuration
        qsTr("Device Registration"          ), // DeviceRegistration
        qsTr("Software Update"              ), // SWUpdate
        qsTr("Enable Root SSH"              ), // RootSSHAccess
        qsTr("Factory Reset"                ), // FactoryReset
        qsTr("Decommissioning"              ), // Decommission
        qsTr("Institutional Configurations" ), // Institutional Configurations
    ]
    property var itemsEnabled   : [
        true                                , // Information
        true                                , // VolumeBrightness
        true                                , // WiFi
        true                                , // Bluetooth
        true                                , // DGCleaning
        true                                , // DGScheduling
        true                                , // ServicePassword
        true                                , // SetDateTime
        true                                , // ExportLogs
        true                                , // Language
        true                                , // RoInput
        true                                , // Calibration
        true                                , // Device Configuration
        true                                , // DeviceRegistration
        true                                , // SWUpdate
        true                                , // RootSSHAccess
        true                                , // FactoryReset
        true                                , // Decommission
        true                                , // Institutional Record
    ]
    property var itemsVisible  : [
        visibleInformation                  , // Information
        visibleVolumeBrightness             , // VolumeBrightness
        visibleWiFi                         , // WiFi
        visibleBluetooth                    , // Bluetooth
        visibleDGCleaning                   , // DGCleaning
        visibleDGScheduling                 , // DGScheduling
        visibleServicePassword              , // ServicePassword
        visibleSetDateTime                  , // SetDateTime
        visibleExportLogs                   , // ExportLogs
        visibleLanguage                     , // Language
        visibleRoInput                      , // RoInput
        visibleCalibration                  , // Calibration
        visibleDeviceConfiguration          , // Device Configuration
        visibleDeviceRegistration           , // DeviceRegistration
        visibleSWUpdate                     , // SWUpdate
        visibleRootSSHAccess                , // RootSSHAccess
        visibleFactoryReset                 , // FactoryReset
        visibleDecommission                 , // Decommission
        visibleInstitutionalRecord          , // Institutional Record
    ]

    SettingsHome { id   : _settingsHome
        title           : _GuiView.manufactSetup
                          ? qsTr("Manufacturing Setup")
                          : serviceMode
                            ? qsTr("Service")
                            : _GuiView.updateSetup
                              ? qsTr("Software Update")
                              : _GuiView.registerSetup
                                ? qsTr("Device Registration ")
                                : qsTr("Device Settings")
        backVisible     : false
        //TODO  on graceful shutdown, the applicaiton quit shall be used for any applicaiton termination
        //      and needs to be distinguished between the QUIT or SHUTDOWN touch,
        //      to know whether to run the lockdown scropt or just quit the app.
        confirmVisible  : serviceMode           || _GuiView.updateMode || _GuiView.registerMode
        confirmText.text: _GuiView.manufactMode || _GuiView.updateMode || _GuiView.registerMode ? qsTr("COMPLETE") : qsTr("SHUTDOWN")
        onConfirmClicked: {
            if ( _GuiView.manufactSetup || _GuiView.updateSetup || _GuiView.registerSetup ) {
                _GuiView.doQuitApplication()
            }
            else {
                _GuiView.doActionTransmit(GuiActions.ID_PowerOff, GuiActions.NoData)
            }
        }
        itemsText       : _root.itemsText
        itemsEnabled    : _root.itemsEnabled
        itemsVisible    : _root.itemsVisible
        onItemClicked   : {
            vDevice.status = ""
            switch (vIndex) {
            case SettingsStack.Information:
                vAdjustmentVersions     .doAdjustment()
                vAdjustmentServiceDates .doAdjustment()
                vHDUsageInfo            .doAdjustment()
                push(_settingsInformation)
                break

            case SettingsStack.VolumeBrightness:
                vDevice.doInitBrightness()
                push(_settingsVolumeBrightness)
                break

            case SettingsStack.WiFi:
                vNetwork.doInit()
                push( _settingsWiFi )
                // _settingsWiFi.setFocus() // No keyboard popup.
                break

            case SettingsStack.Bluetooth:
                push( _settingsBluetooth )
                break

            case SettingsStack.DGCleaning:
                push( _settingsDGCleaning )
                break

            case SettingsStack.DGScheduling:
                push( _settingsDGScheduling )
                break

            case SettingsStack.ServicePassword:
                push(_servicePassword)
                _servicePassword.setFocus()
                break

            case SettingsStack.SetDateTime:
                vDateTime.doInit()
                push( _settingsDateTime )
                _settingsDateTime.setFocus()
                break

            case SettingsStack.ExportLogs:
                push( _settingsExportLogs )
                break

            case SettingsStack.RoInput:
                push( _settingsRoInput )
                break

            case SettingsStack.DeviceConfiguration:
                push( _settingsDeviceConfiguration )
                break

            case SettingsStack.DeviceRegistration:
                push( _settingsDeviceRegistration )
                break

            case SettingsStack.RootSSHAccess:
                vDevice.doInitRootSSHAccess()
                push( _SettingsRootSSHAccess)
                break

            case SettingsStack.FactoryReset:                
                push( _serviceFactoryReset )
                break

            case SettingsStack.Decommission:
                push( _serviceDecommission )
                break

            case SettingsStack.InstitutionalRecord:
                vAdjustmentInstitutionalRecord.doAdjustment()
                push( _settingsInstitutionalRecord )
                break

            default:
                console.debug("Unknown Index", vIndex)
                break
            }
        }
    }

    SettingsInformation         { id: _settingsInformation          }
    SettingsVolumeBrightness    { id: _settingsVolumeBrightness     }
    SettingsWiFi                { id: _settingsWiFi                 }
    SettingsBluetoothCuff       { id: _settingsBluetooth            }
    SettingsDGCleaning          { id: _settingsDGCleaning           }
    SettingsDGScheduling        { id: _settingsDGScheduling         }
    SettingsServicePassword     { id: _servicePassword              }
    SettingsDateTime            { id: _settingsDateTime             }
    SettingsExportLogs          { id: _settingsExportLogs           }
    SettingsROInput             { id: _settingsRoInput              }
    SettingsManufacturingSetup  { id: _settingsDeviceConfiguration  }
    SettingsDeviceRegistration  { id: _settingsDeviceRegistration   }
    SettingsRootSSHAccess       { id: _SettingsRootSSHAccess        }
    SettingsFactoryReset        { id: _serviceFactoryReset          }
    SettingsDecommission        { id: _serviceDecommission          }
    SettingsInstitutionalRecord { id: _settingsInstitutionalRecord  }

    function gotoServiceMode( vservice ) {
        //DEBUG console.log (" 0 ---------- ", _GuiView.manufactMode, _GuiView.manufactSetup, _GuiView.registerMode, _GuiView.registerSetup, vservice, stackView.initialItem, stackView.currentItem, stackView.depth)
        if ( ! _servicePassword.isPassword_Accepted ) return
        serviceMode      = vservice
        if ( vservice )
            _mainMenu.hidden = true
        else
            if ( _settingsHome.visible )
                _mainMenu.hidden = false
    }

    Connections { target: vAdjustmentServiceMode
        function onAdjustmentTriggered              ( vValue ) {
            if ( vAdjustmentServiceMode.adjustment_Accepted ) {
                _settingsHome.notificationText = ""
            }
            else {
                _settingsHome.notificationText = vAdjustmentServiceMode.text()
            }
        }
    }

    Connections { target: vAdjustmentInstitutionalRecord
        function onAdjustmentTriggered              ( vValue ) {
            if ( vAdjustmentInstitutionalRecord.adjustment_Accepted ) {
                _settingsHome.notificationText = ""
            }
            else {
                _settingsHome.notificationText = vAdjustmentInstitutionalRecord.text()
            }
        }
    }

    Connections { target: vHDOperationMode
        function onServiceChanged                   ( vValue ) { gotoServiceMode(                         vValue  )}
        function onStandbyWaitDisinfectChanged      ( vValue ) { page( _settingsHome                    , vValue  )}
    }

    Connections { target: _GuiView
        function onManufactModeChanged( vPass ) {
            if ( _GuiView.manufactMode )  {
                vSettings.checkServicePasswordSet()
                stackView.initialItem =  _servicePassword
            }
            else {
                stackView.initialItem = _settingsHome
            }
            push(stackView.initialItem)

            //DEBUG console.log (" 1 ---------- ", _GuiView.manufactMode, _GuiView.manufactSetup, _GuiView.registerSetup, vPass, stackView.initialItem, stackView.currentItem, stackView.depth)
            if ( _GuiView.manufactSetup ) {
                _settingsHome.notificationText = vPass ? "" : qsTr("Application POST Failed, please shutdown and retry")
            }
        }
        function onUpdateModeChanged( vPass ) {
            if ( _GuiView.UpdateMode )  {
                stackView.initialItem = _settingsHome
            }
            push(stackView.initialItem)

            //DEBUG console.log (" 1 ---------- ", _GuiView.manufactMode, _GuiView.manufactSetup, vPass, stackView.initialItem, stackView.currentItem, stackView.depth)
            if ( _GuiView.updateSetup ) {
                _settingsHome.notificationText = vPass ? "" : qsTr("Application POST Failed, please shutdown and retry")
            }
        }
        function onRegisterModeChanged( vPass ) {
            if ( _GuiView.registerMode )  {
                stackView.initialItem = _settingsHome
            }
            push(stackView.initialItem)

            //DEBUG console.log (" 1 ---------- ", _GuiView.manufactMode, _GuiView.manufactSetup, vPass, stackView.initialItem, stackView.currentItem, stackView.depth)
            if ( _GuiView.registerSetup ) {
                _settingsHome.notificationText = vPass ? "" : qsTr("Application POST Failed, please shutdown and retry")
            }
        }
    }

    onVisibleChanged: {
        if (visible) {
            _mainMenu.hidden = serviceMode || _GuiView.manufactSetup
        }
        else {
            stackView.initialItem = null
        }
    }
}
