/*
    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 QtGraphicalEffects 1.0
//import QtQuick.Templates 2.04 as T
//import QtQuick.Controls.impl 2.04
import QtQuick.Controls.Material 2.3

import "../Components"

Page {
    id: root

    enum WidgetType {
        Competitions,

        Profile,

        Registration,
        Startlist,
        Result,

        Ranking,
        Aggregated, // not yet implemented

        Invalid
    }

    title: widgetLd.item !== null && widgetLd.item.hasOwnProperty('title') ? widgetLd.item['title']:""
    property string subTitle:  widgetLd.item !== null && widgetLd.item.hasOwnProperty('subTitle') ? widgetLd.item['subTitle']:""
    property bool titleIsPageTitle: widgetLd.item !== null && widgetLd.item.hasOwnProperty('titleIsPageTitle') ? widgetLd.item['titleIsPageTitle']:false
    property Component headerComponent: widgetLd.item !== null && widgetLd.item.hasOwnProperty('headerComponent') ? widgetLd.item['headerComponent']:null

    function onBackRequested() {
        return !widgetLd.item.hasOwnProperty('onBackRequested') || widgetLd.item.onBackRequested()
    }

    property var params

    property int status: -1
    property bool ready: false

    property var widgetData

    property int widgetType

    Component.onCompleted: {
        loadData(params)
    }

    function loadData(params) {
        // params is an object and can contain: {
        //  comp: competitionId,
        //  person: personId,
        //  cat: categoryId,
        //  nation: nationString ('', 'GER', 'SUI')
        //  route: (int) round
        //  type: ('','starters', 'nat_team_ranking', 'sektionenwertung', 'regionalzentren'),
        //}
        var ret = serverConn.getWidgetData(params)

        root.status = ret["status"]

        if(ret["status"] === 200){
            root.widgetData = ret["data"]
            root.widgetType = checkWidgetType(params, root.widgetData)
            if(widgetType === WidgetPage.WidgetType.Invalid) {
                root.ready = false
                root.status = 906
            }
            else if(widgetLd.load()){
                root.ready = true
            }
            else {
                //root.status = 901
                root.ready = false
            }
        }
        else if(ret["status"] === 404 &&
                [
                    WidgetPage.WidgetType.Registration,
                    WidgetPage.WidgetType.Startlist,
                    WidgetPage.WidgetType.Result
                ].includes(root.widgetType) &&
                root.params["route"] !== "") {
            // if we get a 404 and have startlist, results or registration, the route was not found -> remove round and try again
            root.params["route"] = ""
            loadData(root.params)
            return
        }
        else {
            root.ready = false
        }

        app.errorCode = root.status

    }

    function updateData(params, openLoadingDl) {
        if(openLoadingDl)
            loadingDl.open()

        // update all the given values
        Object.assign(root.params, params)

        loadData(root.params)

        console.log("ready: " + root.ready + ": " + root.status)

        if(openLoadingDl)
            loadingDl.close()

    }

    function areParamsValid() {

    }

    function checkWidgetType(params, widgetData){
        var widgetType

        function hasParam(object, key, value){
            if(object[key] !== undefined){
                if(value !== undefined){
                    return object[key] === value
                }
                return true
            }
            return false
        }

        // check the type of the requested widget

        if(hasParam(params, 'person')){
            // person profile
            widgetType = WidgetPage.WidgetType.Profile
        }

        else if(hasParam(params, 'nation')){
            // competition calendar
            widgetType = WidgetPage.WidgetType.Competitions
        }

        else if(hasParam(params, 'comp') && hasParam(params, 'type', 'starters')){
            // registration
            widgetType = WidgetPage.WidgetType.Registration
        }
        else if(hasParam(params, 'type', 'startlist') || (widgetData.participants !== undefined && widgetData.participants[0] && !widgetData.participants[0].result_rank && widgetData.discipline !== 'ranking')){
            // startlist
            widgetType = WidgetPage.WidgetType.Startlist
        }
        else if(hasParam(params, 'comp') && hasParam(params, 'cat')){
            // results
            widgetType = WidgetPage.WidgetType.Result
        }

        else if( hasParam(params, 'cat') && hasParam(params, 'cup') && !hasParam(params, 'comp')){
            // ranking data
            widgetType = WidgetPage.WidgetType.Ranking
        }
        else if(hasParam(params, 'type', 'nat_team_ranking') || hasParam(params, 'type', 'sektionenwertung') || hasParam(params, 'type', 'regionalzentren')){
            // aggregated
            widgetType = WidgetPage.WidgetType.Aggregated
        }
        else {
            widgetType = WidgetPage.WidgetType.Invalid
        }

        return widgetType
    }

    function encodeQueryData(data) {
       const ret = [];
       for (let d in data)
         ret.push(encodeURIComponent(d) + '=' + encodeURIComponent(data[d]));
       return ret.join('&');
    }

    function shareWidget(compName) {
        var url = "https://l.bluerock.dev/?" + encodeQueryData(params)
        sharePu.appear(url, compName)
    }

    Loader {
        id: widgetLd

        property alias selector: selectorPu
        property var updateData: root.updateData
        property alias params: root.params
        property alias currentWidgetData: root.widgetData
        property bool isTopElement: mainStack.currentItem === root

        property var oldWidgetType: NaN

        anchors.fill: parent

        source: ""

        function load() {
            if(root.widgetType !== oldWidgetType){
                oldWidgetType = root.widgetType
                var calComp = Qt.createComponent(getFile(root.widgetType))//.createObject(null, {widgetData: root.widgetData, parent: widgetLd})

                widgetLd.sourceComponent = calComp
                //widgetLd.item.widgetData = root.widgetData
            }
            root.status = widgetLd.item.status

            if(widgetLd.item.ready){
                return true
            }
            else {
                root.status = widgetLd.item.status === undefined ? 900:widgetLd.item.status
                delete(widgetLd.sourceComponent)
                return false
            }
        }

        function getFile(widgetType) {
            var path = "qrc:/Widgets/"
            switch(widgetType){
            case WidgetPage.WidgetType.Competitions:
                path += "CalendarWidget"
                break
            case WidgetPage.WidgetType.Profile:
                path += "ProfileWidget"
                break
            case WidgetPage.WidgetType.Registration:
                path += "RegistrationWidget"
                break
            case WidgetPage.WidgetType.Startlist:
                path += "StartlistWidget"
                break
            case WidgetPage.WidgetType.Result:
                path += "ResultWidget"
                break
            case WidgetPage.WidgetType.Ranking:
                path += "RankingWidget"
                break

            }

            path += ".qml"
            return path
        }

        function getItemProperty(key, defaultValue) {
            if(widgetLd.item !== null && widgetLd.item.hasOwnProperty(key)) {
                return key
            }
            else {
                return defaultValue
            }
        }

    }

    SelectorPopup {
        id: selectorPu

        Material.theme: root.Material.theme

        contentItem: ListView {
            id: selectorLv

            property int delegateHeight: 50
            spacing: 10
            clip: true

            implicitHeight: model === 0 ? 0:(delegateHeight + spacing) * model

            model: selectorPu.dataObj !== undefined ? selectorPu.dataObj.length:0

            ScrollIndicator.vertical: ScrollIndicator {
                parent: selectorLv.parent
                anchors {
                    top: selectorLv.top
                    left: selectorLv.right
                    margins: 10
                    leftMargin: 3
                    bottom: selectorLv.bottom
                }
            }

            delegate: Button {
                id: catBt

                width: selectorLv.width
                height: text !== "" ? selectorLv.delegateHeight:0

                flat: true

                text: selectorPu.dataObj[index].text

                onClicked: {
                    selectorPu.close()
                    selectorPu.selectionFinished(index, selectorPu.dataObj[index].data)
                }
            }
        }
    }

    SharePopup {
        id: sharePu

        Material.theme: root.Material.theme
    }
}
