/*!
 *
 * 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 Service Password") : qsTr("Service 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

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

        // ask HD to go to service mode
        vAdjustmentServiceMode.doAdjustment()

        // 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 ( vHDOperationMode.service   ) gotoServiceMode(true)

        // if NoCANBus is set don't wait for HD and go to service mode.
        if ( vSettings.noCANBus         ) gotoServiceMode(true)
    }

    function checkPassword() {
        if ( ! vSettings.isServicePasswordMatch( passwordCurrent ) ) { _root.notificationText = qsTr("Incorrect password"   ); return false }

        if ( ! passwordChangeMode                                  ) { _root.notificationText = ""                           ; return true  }

        if (    passwordConfirm !=       passwordUpdated           ) { _root.notificationText = qsTr("Mismatch Passwords"   ); return false }
        if ( ! vSettings.isPasswordValid(passwordUpdated         ) ) { _root.notificationText = qsTr("Invalid Password"     ); return false }

                                                                       _root.notificationText = ""                           ; return true
    }
}
