/*!
 *
 * Copyright (c) 2023-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    SettingsServicePassword.qml
 * \author  (last)      Behrouz NematiPour
 * \date    (last)      28-Aug-2023
 * \author  (original)  Behrouz NematiPour
 * \date    (original)  18-Jul-2023
 *
 */

// Qt
import QtQuick                  2.12

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

/*!
 * \brief   SettingsServicePassword is the screen
 *          which asks service password
 */
UserConfirmation{ id: _root
    itemIndex       : SettingsStack.ServicePassword

             property bool isPassword_Accepted       : false
    readonly property bool isDefaultServicePassword  : vSettings.isDefaultServicePassword

    isPassword          :   true
    backVisible         : ! _GuiView.manufactSetup
    passwordChangeMode  :   isDefaultServicePassword && _GuiView.manufactSetup
    title               :   passwordChangeMode ? qsTr("Set Password") : qsTr("Enter Password")

    onBackClicked       : {
        clearPasswords()
        _settingsHome.notificationText = ""
    }

    onConfirmClicked: {
        // check for password(s), and check the accepeted flag
        isPassword_Accepted = checkPassword()

        // if not accepted return
        if ( ! isPassword_Accepted ) return

        // clear the screen
        _root.notificationText = ""
        clearPasswords()

        // go back to the settings home/menu screen
        page(_settingsHome)

        // in case of debugging that the HD is in service mode already check and call the gotoServiceMode
        if ( vTDOpMode.service   ) gotoServiceMode(true)
    }

    function checkPassword() {
        let servicePasswordCheck    = false
        let user1PasswordCheck      = false // does nothing right now

        if ( vSettings.isServicePasswordMatch( passwordCurrent ) ) {
            if (passwordChangeMode) {
                handleServicePassword()
            }

            servicePasswordCheck = true
        }

        // TODO: Add other password match checks for other users
//        if ( vSettings.isUser1PasswordMatch( passwordCurrent ) || passwordChangeMode    ){ handleUser1Password();   user1PasswordCheck = true   }

        // check all password check if any are successful
        let allPasswordCheck = servicePasswordCheck || user1PasswordCheck
        _root.notificationText = allPasswordCheck ? "" : qsTr("Incorrect password")

        return allPasswordCheck
    }

    function handleServicePassword() {
        // if accepted save the password
        if (   passwordChangeMode ) vSettings.updateServicePassword(passwordUpdated)

        // ask TD to go to service mode
        vAdjustmentServiceMode.doAdjustment()
    }
}
