/*
    blueROCK - for digital rock
    Copyright (C) 2019  Dorian Zedler

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

import QtQuick 2.9
import QtQuick.Controls 2.4
import QtQuick.Layouts 1.3
import QtGraphicalEffects 1.0
import QtQuick.Controls.Material 2.3
import QtPurchasing 1.12

import "../Components"

DataListView {
    id: control

    property bool ready

    property string title: control.widgetData['comp_name']
    property string subTitle: getSubtitle()
    property bool titleIsPageTitle: true

    property Component headerComponent: RowLayout {

        height: parent.height
        spacing: 0

        layoutDirection: Qt.RightToLeft

        ToolButton {
            id: moreToolBt

            onClicked: control.changeCat()

            text: "\uf142"
            font.family: fa5solid.name
        }

        ToolButton {
            id: flowToolBt

            visible: speedFlowChartPopup.enabled

            enabled: control.widgetData['route_order'] === "-1" && Object.keys(control.widgetData['route_names']).length > 2

            onClicked: {
                control.positionViewAtBeginning()
                speedFlowChartPopup.toggle()
            }

            text: "\uf0e8"
            font.family: fa5solid.name
        }

        ToolButton {
            id: shareToolBt

            onClicked: shareWidget(control.title)

            text: "\uf1e0"
            font.family: fa5solid.name
        }
    }

    property var widgetData: currentWidgetData

    Component.onCompleted: {
        if(model > 0){
            control.ready = true
            control.status = 200
        }
        else {
            control.ready = false
            control.status = 901
        }

        if(!control.ready)
            return

        //model = widgetData[ "participants" ] === undefined ? 0:widgetData[ "participants" ].length
        //routeSelectTb.setCurrentIndex(routeSelectTb.getIndex(parseInt(control.widgetData['route_order'])))
    }

    model: widgetData[ "participants" ] === undefined ? 0:widgetData[ "participants" ].length

    onRefresh: {
        updateData({}, false)
    }

    onWidgetDataChanged: {
        console.log("widget data changed")

        if(control.widgetData['discipline'] === 'speed' && control.widgetData['route_order'] === "-1" && Object.keys(control.widgetData['route_names']).length > 2){
            speedFlowChartPopup.flowchartData = ({})
            speedFlowChartPopup.flowchartData = control.widgetData
            speedFlowChartPopup.enabled = true
        }
        else {
            speedFlowChartPopup.flowchartData = ({})
            speedFlowChartPopup.enabled = false
        }
    }

    function onBackRequested() {
        if(!speedFlowChartPopup.isVisible())
            return true

        speedFlowChartPopup.toggle()
        return false
    }

    function getSubtitle() {
        var titleString = control.widgetData["route_name"]

        //% "(Results)"
        var addition = qsTrId("#resultsHeadline")

        if(titleString)
            return addition + " " + titleString
        else
            return ""
    }

    function changeRoute(route) {
        updateData({route:route}, true)
    }

    function changeCat(){
        var cats = control.widgetData["categorys"]

        cats.sort(function(a, b) {
            return parseInt(a["GrpId"]) - parseInt(b["GrpId"]);
        });

        var selectOptions = []

        for(var prop in cats){
            if (cats.hasOwnProperty(prop) && parseInt(cats[prop]["GrpId"]) !== parseInt(params.cat)) {
                // append all cats and ignore the current one
                //console.log("found cat: ", cats[prop]['name'])
                selectOptions.push({text: cats[prop]['name'], data:{cat: cats[prop]['GrpId']}})
            }
        }

        selector.appear(selectOptions, qsTrId("#selectCategory"))
    }

    Connections {
        target: selector
        function onSelectionFinished(index, data) {
            if(data.cat !== undefined){
                updateData({cat: data.cat}, true)
            }
        }
    }

    onContentYChanged: {
        if(contentY > 0 && speedFlowChartPopup.state === "visible"){
            control.positionViewAtBeginning()
        }
    }

    delegate: ResultDelegate {
        enabled: speedFlowChartPopup.state === "hidden"
    }

    footer: ItemDelegate {
        height: routeSelectTb.height
    }

    RectangularGlow {
        id: toolBarEffect
        glowRadius: 3
        spread: 0.2
        color: "black"
        opacity: 0.3
        anchors.fill: routeSelectTb
    }

    TabBar {
        id: routeSelectTb

        property var tabs: getTabs()
        property var tabIndexes: []

        enabled: speedFlowChartPopup.state === "hidden"

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

        height:  tabs.length > 1 ? 50:0
        width: parent.width

        position: TabBar.Footer

        currentIndex: getIndex(parseInt(control.widgetData['route_order']))

        function getTabs() {

            var obj = control.widgetData["route_names"]
            var buttonData = []

            for(var prop in obj) {
                // go through the whole array and search for data keys
                if (obj.hasOwnProperty(prop)) {
                    buttonData.push([prop, obj[prop]])
                    //console.log("found " + obj[prop] + " at index " + prop)
                }
            }

            buttonData.sort(function(a, b) {
                return a[0] - b[0];
            });

            return buttonData
        }

        function getIndex(routeNumber) {
            //console.log("getting index for route number: " + routeNumber)

            if(tabs === undefined){
                //return
            }

            for(var i = 0; i < tabs.length; i++){
                //console.log(tabs[i])
                if(parseInt(tabs[i][0]) === routeNumber){
                    //console.log("found index: " + i)
                    return i
                }
            }


            return 0
        }

        Repeater {
            id: routeSelectButtonRep

            model: routeSelectTb.tabs.length

            onModelChanged: {
                routeSelectTb.setCurrentIndex(routeSelectTb.getIndex(params.route))
            }

            delegate: TabButton {
                text: routeSelectTb.tabs[index][1]

                width: Math.max(150, routeSelectTb.width / routeSelectButtonRep.model) //text.length * font.pixelSize

                onClicked: {
                    //console.log("changing to index: " + index + " (" + routeSelectTb.tabs[index][0] + ", " + routeSelectTb.tabs[index][1] + ")")
                    if(routeSelectTb.getIndex(parseInt(control.widgetData['route_order'])) !== index){
                        control.changeRoute(routeSelectTb.tabs[index][0])
                        routeSelectTb.setCurrentIndex(routeSelectTb.getIndex(parseInt(control.widgetData['route_order'])))
                    }
                }
            }
        }

    }

    SpeedFlowChartPopup {
        id: speedFlowChartPopup
    }

    PullRefresher {
        // has to be placed here again,
        // to be on top of the speed flowchart
        target: control

        postRefreshDelay: 0

        busyIndicator: FancyBusyIndicator {}
        refreshPosition: height * 1.3

        onRefreshRequested: {
            control.refresh()
        }
    }


}
