import QtQuick 2.15
import QtQuick.Controls 2.15
import QtQuick.Controls.Material 2.15

Rectangle {
    id: control

    property var flowchartData: ({})

    // always unlock in debug mode
    //property bool unlocked: QT_DEBUG || appSettings.read("speedBackendPurchase") === "1"
    property bool unlocked: Qt.platform.os !== "iso" || appSettings.read("speedBackendPurchase") === "1"

    Component.onCompleted: {
        console.warn("unlocked:", appSettings.read("speedBackendPurchase"))
    }

    state: "hidden"

    anchors {
        top: parent.top
        bottom: parent.bottom
        left: parent.right
    }

    width: parent.width
    height: parent.height

    color: Material.background

    onStateChanged: reloadState()
    onUnlockedChanged: reloadState()

    function toggle() {
        if(control.state === "hidden"){
            control.state = "visible"
        }
        else {
            control.state = "hidden"
        }
    }

    function isVisible() {
        return control.state === "visible"
    }

    function reloadState() {
        if(state === "visible" && unlocked) {
            speedFlowChartLoader.sourceComponent = speedFlowChartComponent
        }
        else if(state === "visible" && !unlocked) {
            speedFlowChartLoader.sourceComponent = speedFlowChartLockerComponent
        }
        else {
            speedFlowChartLoader.sourceComponent = undefined
        }
    }

    Connections {
        target: speedFlowChartProduct
        function onPurchaseRestored() {
            control.unlocked = appSettings.read("speedBackendPurchase") === "1"
        }

        function onPurchaseSucceeded() {
            control.unlocked = appSettings.read("speedBackendPurchase") === "1"
        }
    }

    Loader {
        id: speedFlowChartLoader

        anchors.fill: parent

        Component {
            id: speedFlowChartComponent
            SpeedFlowChart {
                anchors.fill: parent
                anchors.margins: 10

                flowchartData: control.flowchartData
            }
        }

        Component {
            id: speedFlowChartLockerComponent

            SpeedFlowChartLocker {

            }

        }
    }

    states: [
        State {
            name: "hidden"
            PropertyChanges {
                target: control
                opacity: 0
                anchors.leftMargin: 0
            }
        },

        State {
            name: "visible"
            PropertyChanges {
                target: control
                opacity: 1
                anchors.leftMargin: -parent.width
            }
        }
    ]

    transitions: [
        Transition {
            NumberAnimation {
                properties: "opacity,scale,anchors.leftMargin"
                duration: 200
                easing.type: Easing.InOutQuad
            }
        }
    ]
}
