/*!
 *
 * 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    SettingsWiFi.qml
 * \author  (last)      Behrouz NematiPour
 * \date    (last)      18-Jul-2023
 * \author  (original)  Behrouz NematiPour
 * \date    (original)  06-May-2021
 *
 */

// Qt
import QtQuick 2.15

// Project

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

/*!
 * \brief   SettingsWiFi
 *          The settings screen to setup the WiFi connection
 */
SettingsBase    { id: _root
    itemIndex       : SettingsStack.WiFi

    property var ipValidator: RegExpValidator {
        regExp:/^(([01]?[0-9]?[0-9]|2([0-4][0-9]|5[0-5]))\.){3}([01]?[0-9]?[0-9]|2([0-4][0-9]|5[0-5]))$/
    }

    labelWidth    : 200
    entryWidth    : 175

    readonly property int spacing       : 20
    readonly property int leftMargin    : 50
    readonly property int rightMargin   : 50
    readonly property int topMargin     : 160
    readonly property bool  isConnected : vDevice.ssid !== ""

    confirmVisible  : false

    notificationText: vDevice.status


    contentItem: Item { id: _contentRow
        anchors.fill: parent

        Item { id: _wifiItem
            anchors {
                left            : parent.left
                leftMargin      : Variables.defaultMargin * 2
                top             : contentItem.top
                bottom          : contentItem.bottom
            }

            width   : parent.width / 2.5

            Text { id : _wifiInfoTitle
                anchors {
                    top : parent.top
                    left: parent.left
                }
                width           : parent.width
                height          : 60
                text            :  qsTr("Current Wi-Fi Information")
                font.pixelSize  : Fonts.fontPixelButton
                font.weight     : Font.Medium
                color           : Colors.offWhite

                Line { id: _divider
                    color   : Colors.panelBorderColor
                    anchors {
                        bottom      : parent.bottom
                        bottomMargin: 10
                        left        : parent.left
                        right       : parent.right
                    }
                }
            }

            TouchGrid { id: _currentWifi
                anchors {
                    top : _wifiInfoTitle.bottom
                    left: _wifiInfoTitle.left
                }
                width               : parent.width
                touchable           : false
                alignCenter         : false
                rowCount            : 5
                colCount            : 1
                itemWidth           : width
                itemsText           : [ qsTr("SSID")        ,
                                        qsTr("IP Address")  ,
                                        qsTr("Gateway")     ,
                                        qsTr("Subnet Mask") ,
                                        qsTr("DNS")         ]
                lineColor           : Colors.panelBorderColor

                itemsValue          : [ vDevice.ssid                                ,
                                        _root.isConnected ? vDevice.ipAddress : ""  ,
                                        vDevice.gateway                             ,
                                        vDevice.subnetMask                          ,
                                        vDevice.dns                                 ]

                delegateColor       :  Colors.transparent
                itemsHasLine        :  Array(itemsText.length).fill(true) // sets all to true
                itemsHasImage       :  Array(itemsText.length).fill(false) // sets all to false
            }
        }

        Rectangle { id: _networkRect
            color       : Colors.panelBackgroundColor
            anchors {
                right           : parent.right
                rightMargin     : Variables.defaultMargin * 2
                top             : contentItem.top
                bottom          : contentItem.bottom
            }
            width       : parent.width / 2.5

            Column { id: _networkColumn
                anchors.fill: parent

                Rectangle { id: _header
                    width       : parent.width
                    height      : 75
                    color       : Colors.panelBackgroundColor
                    radius      : 9

                    border {
                        width: 1
                        color: Colors.panelBorderColor
                    }

                    Text { id: _title
                        text                : qsTr("Available Networks")
                        color               : Colors.offWhite
                        font.family         : Fonts.fontFamilyFixed
                        font.weight         : Font.DemiBold
                        font.pixelSize      : Fonts.fontPixelTextRectTitle
                        anchors {
                            left            : parent.left
                            leftMargin      : Variables.defaultMargin
                            verticalCenter  : parent.verticalCenter
                        }
                    }

                    IconButton { id: _refreshIcon
                        anchors {
                            right           : parent.right
                            rightMargin     : Variables.defaultMargin
                            verticalCenter  : parent.verticalCenter
                        }
                        iconSize        : Variables.iconsDiameter
                        iconImageSource : enabled ? "qrc:/images/iRefresh" : "qrc:/images/iRefreshDisabled"
                        enabled         : vDevice.wifiListEnabled

                        onPressed       : vDevice.wifiList = ""
                    }
                }

                Item { id: _wifiListItem
                    width               : parent.width
                    height              : parent.height - _header.height

                    ListView    { id        : _networkList
                        model               : vDevice.model
                        clip                : true
                        width               : parent.width
                        height              : parent.height

                        delegate : TouchRect { id : _delegate
                            readonly property color  networkDelegateTextColor   : wifiSupported ? Colors.offWhite : Colors.textDisableButton
                            readonly property string postSecurityTypeLabel      : wifiSupported ? "" : " - " + qsTr("Not Supported")
                            readonly property bool   isConnected                : wifiConnected
                            readonly property int margin                        : Variables.defaultMargin * 2
                            onIsConnectedChanged: {
                                if ( isConnected ) {
                                    vDevice.doInitWifiInfo()
                                }
                            }

                            clip                            : true
                            text.text                       : wifiSsid
                            text.elide                      : Text.ElideLeft
                            text.color                      : _delegate.networkDelegateTextColor
                            width                           : parent.width
                            height                          : 75
                            radius                          : 0
                            backgroundColor                 : Colors.waterSampleContainer
                            pixelSize                       : Fonts.fontPixelTextRectTitle
                            text.font.weight                : Font.Medium
                            text.anchors.horizontalCenter   : undefined
                            text.anchors.verticalCenter     : undefined

                            text.horizontalAlignment        : Text.AlignLeft
                            text.leftPadding                : _delegate.margin
                            text.topPadding                 : 10
                            text.verticalAlignment          : Text.AlignTop
                            border.width                    : 0

                            Text { id           : _securityLevel
                                anchors {
                                    left        : parent.left
                                    leftMargin  : _delegate.margin
                                    bottom      : parent.bottom
                                    bottomMargin: 5
                                }
                                font.pixelSize  : Fonts.fontPixelDialogText
                                font.weight     : Font.Light
                                text            : wifiSecurityTypes + _delegate.postSecurityTypeLabel
                                color           : _delegate.networkDelegateTextColor
                            }

                            Text { id           : _isConnected
                                anchors {
                                    verticalCenter  : parent.verticalCenter
                                    right           : parent.right
                                    rightMargin     : _delegate.margin
                                }
                                font.pixelSize  : Fonts.fontPixelTextRectExtra
                                font.weight     : Font.Medium
                                text            : wifiConnected ? qsTr("Connected") : ""
                                color           : Colors.statusTextActive
                            }

                            Line { id: _wifiDivider
                                color   : Colors.panelBorderColor
                                visible : index !== _networkList.count - 1
                                anchors {
                                    bottom      : parent.bottom
                                    left        : parent.left
                                    leftMargin  : _delegate.margin
                                    right       : parent.right
                                    rightMargin : _delegate.margin
                                }
                            }

                            onClicked           : {
                                if( wifiSupported ) {
                                    _wifiConfirmDialog.isPassword   = ! wifiConnected
                                    _wifiConfirmDialog.ssid         =   wifiSsid
                                    _wifiConfirmDialog.open()
                                }
                            }
                        }
                    }

                    ScrollBar {
                        flickable           : _networkList
                        anchors.fill        : _networkList
                        scrollColor         : Colors.scrollBarColor
                        handleWidth         : 5
                        visible             : _networkList.count > 0
                    }
                }
            }
        }
    }

    ConfirmDialog   { id: _wifiConfirmDialog
        property bool   isPassword              : false
        property string ssid                    : ""
        property string separator               : "\n"
        readonly property string spaceSeparator : " "
        height                      : Variables.completeDialogHeight - 130 // need to make room for keyboard
        width                       : Variables.completeDialogWidth
        y                           : 0
        titleText                   : isPassword ? qsTr("Join") + separator + ssid :
                                       qsTr("Disconnect") + separator + ssid
        messageText                 : isPassword ? qsTr("Password") : qsTr("Do you want to disconnect from `%1`?").arg(ssid)
        messageTextPixel            : Fonts.fontPixelTextRectExtra
        notificationText            : vDevice.status

        Item { id: _passwordItem
            readonly    property string passwordCurrent : _passwordEntry.textInput.text
            visible         : _wifiConfirmDialog.isPassword
            anchors.centerIn: parent

            TextEntry { id: _passwordEntry
                clip                        : true
                textInput   .width          : 450
                textInput.inputMethodHints  : Qt.ImhNone
                textInput.echoMode          : TextInput.Password
                anchors.horizontalCenter    : parent.horizontalCenter
                label.text                   : ""
                label.width                  :  0
                lengthMax                    : 30

                onTextChanged: {
                    // Replace non-ASCII characters as they are typed in
                    var filtered = text.replace(/[^\x00-\x7F]/g, "")
                    if (text !== filtered) { text = filtered }  // revert invalid characters
                }
            }

            onVisibleChanged: if ( visible ) _passwordEntry.textInput.forceActiveFocus()
        }

        onAccepted    : {
            if ( isPassword ) {
                if(  _passwordItem.passwordCurrent.length > 0 ) {
                    vDevice.doWifiConnect( true, ssid, _passwordItem.passwordCurrent )
                }
            } else {
                vDevice.doWifiConnect( false, ssid, "" )
            }
        }
    }
}
