import QtQuick 2.12
import QtQuick.Controls 2.12
import QtQuick.Layouts 1.12

import Controls 1.0 as Controls
import Cubo 1.0
import Utils 1.0

Dialog {
    id: root
    title: qsTr("Connection screen")
    width: 400
    height: 320
    modal: true
    closePolicy: Popup.CloseOnEscape


    header: Controls.DialogHeader {
        dialog: root
    }

    contentItem: Rectangle {
        color: Palette.screenBackgroundColor

        ColumnLayout {
            anchors.fill: parent
            anchors.leftMargin: 45
            anchors.rightMargin: 45
            spacing: 20

            Item {
                Layout.fillHeight: true
            }

            Label {
                text: qsTr("Select serial port")
                Layout.fillWidth: true
                Layout.alignment: Qt.AlignHCenter | Qt.AlignBottom
            }

            Controls.ComboBox {
                id: serialBox
                model: BmsInterface.serialPortNames()
                Layout.fillWidth: true
                Layout.alignment: Qt.AlignCenter
            }

            Controls.Button {
                id: connectButton
                text: qsTr("Connect")
                Layout.fillWidth: true
                Layout.alignment: Qt.AlignHCenter | Qt.AlignTop
                onClicked: {
                    if (BmsInterface.isPortConnected()) {
                        BmsInterface.disconnectPort()
                    } else {
                        var currentPort = BmsInterface.serialPortNames()[serialBox.currentIndex]
                        if (BmsInterface.connectSerial(currentPort)) {
                            root.close()
                        }
                    }
                }
            }

            Item {
                Layout.fillHeight: true
            }
        }
    }

    background: Controls.DialogBackground {}

    onVisibleChanged: {
        x = Qt.binding(function() { return (parent.width - width) / 2})
        y = Qt.binding(function() { return (parent.height - height) / 2})
        serialBox.model = BmsInterface.serialPortNames()
    }

    Connections {
        target: BmsInterface
        onPortConnectedChanged: {
            connectButton.text = BmsInterface.isPortConnected() ? qsTr("Disconnect") : qsTr("Connect")
            serialBox.enabled = !BmsInterface.isPortConnected()
        }
    }
}
