/*
 * Copyright (C) 2013, 2014
 *
 * 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; version 3.
 *
 * 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.4
import Ubuntu.Components 1.3
import Ubuntu.Components.ListItems 1.3 as ListItem
import Ubuntu.Components.Popups 1.3

import QtQuick.XmlListModel 2.0
import Ubuntu.Content 1.1

import "../utils/databasemodule_v2.js" as DB
//import "../."

Page {
    id: importFeeds
    title: i18n.tr("Import Feeds")
    flickable: null

    property list<ContentItem> importItems
    property var activeTransfer
    property list<ContentPeer> peers


    property var headActions: [acConfirmbutton]
    head.actions: repeaterFeedList.opmlList == undefined ? null : headActions
    Action {
        id: acConfirmbutton
        text:  i18n.tr("Confirm")
        iconName: "tick"
        onTriggered: {
            DB.importOPMLobject(repeaterFeedList.opmlList)
            mainView.reloadViews()
            pageStack.pop()
            mainView.refresh()
        }
    }

    Component.onCompleted: {
//        timerPush.start()
    }

    /////////////////////////////////////////////////////////////////////   content hub    start here
    ContentTransferHint {
        anchors.fill: importFeeds
        activeTransfer: importFeeds.activeTransfer
    }

    Connections {
        target: importFeeds.activeTransfer
        onStateChanged: {
            console.log("StateChanged: " + importFeeds.activeTransfer.state);
            if (importFeeds.activeTransfer.state === ContentTransfer.Charged) {
                importFeeds.importItems = importFeeds.activeTransfer.items;
                console.log("importItems[0].url: " + importFeeds.importItems[0].url);
                opmlParser.opmlPath = importFeeds.importItems[0].url
            }
        }
    }

    Connections {
        target: ContentHub
        onImportRequested: {
            console.log ("Import requested: " + transfer.state);
//            titleItem.text = "Imported items";
            importFeeds.activeTransfer = transfer;
            if (importFeeds.activeTransfer.state === ContentTransfer.Charged) {
                importFeeds.importItems = importFeeds.activeTransfer.items;
//                opmlParser.opmlPath = importFeeds.importItems[0].url
            }
        }
    }

    Timer {
        id: timerPush
        interval: 100; running: false; repeat: false; triggeredOnStart: false
        onTriggered: {
//            pageStack.pop()
//            pageStack.push(Qt.resolvedUrl("./ContentPickerDialog.qml"))
            pageStack.push(contentPickerDialog)
        }
    }

    //////////////////////////////////////        content hub
    ContentPickerDialog{
        id: contentPickerDialog
        pickerParent: importFeeds
    }
    /////////////////////////////////////////////////////////////////////   content hub    end here

    /////////////////////////////////////////////////////////////////////   opml content    start here
    Flickable {
        id: scrollArea
        objectName: "repeaterFeedList_flickable"

        clip: true

        anchors {
            fill: parent
            bottomMargin: units.gu(1); topMargin: units.gu(1)
        }

        contentWidth: width
        contentHeight: contentItem.childrenRect.height

        Column {
            anchors {
                left: parent.left; right: parent.right
            }
            height: childrenRect.height
            spacing: units.gu(1)

            Repeater {
                id: repeaterFeedList

                model: 0
                property var opmlList: undefined

                function addOpmlObjs (opmlObjs) {
                    console.log("opmlObjs.length: ", opmlObjs.length)
                    repeaterFeedList.model = opmlObjs.length
                    opmlList = opmlObjs
                }

                Column {
                    id: columnContent
                    anchors {
                        left: parent.left; right: parent.right
                    }
                    height: liStandardRoot.isHidden ? units.gu(6.5) : childrenRect.height
                    clip:true

                    Behavior on height { UbuntuNumberAnimation{} }

                    ListItem.Empty {
                        id: liStandardRoot

                        property var opmlRoot: repeaterFeedList.opmlList == undefined ?
                            undefined : repeaterFeedList.opmlList[index]
                        property bool isHidden: true
                        property alias isChecked: checkboxRoot.checked

                        onIsCheckedChanged: {
                            if (liStandardRoot.isChecked) {
                                liStandardRoot.opmlRoot.isSelected = true
                            }
                            else {
                                liStandardRoot.opmlRoot.isSelected = false
                            }
                        }

                        Row {
                            anchors
                            {
                                top: parent.top; bottom: parent.bottom; left: parent.left;
                                leftMargin: units.gu(1); topMargin: units.gu(0.7); bottomMargin: units.gu(1);
                            }
                            spacing: units.gu(2)

                            CheckBox {
                                id: checkboxRoot
                            }

                            Label{
                                id: labelRootName
                                objectName: "labelTopicName"
                                anchors.verticalCenter: parent.verticalCenter
                                fontSize: "large"
                                text: liStandardRoot.opmlRoot == undefined ? "" : liStandardRoot.opmlRoot.text
                            }
                        }

                        Icon{
                            id: imgArrow
                            anchors
                            {
                                right: parent.right; top: parent.top; bottom: parent.bottom;
                                topMargin: units.gu(1.5); bottomMargin: units.gu(1.5); rightMargin: units.gu(2)
                            }
                            name: "go-to"

                            Behavior on rotation { UbuntuNumberAnimation{} }

                            states: [
                                State {
                                    name: "expanded"
                                    when: !liStandardRoot.isHidden

                                    PropertyChanges
                                    {
                                        target: imgArrow
                                        rotation: 90
                                    }
                                }
                            ]
                        }

                        onClicked:
                        {
                            isHidden = !isHidden
                        }
                    }

                    Repeater {
                        id: repeaterFeedsChildren
                        model: liStandardRoot.opmlRoot == undefined ?
                                   "" : liStandardRoot.opmlRoot.children

                        ListItem.Standard {
                            id: listitemFeed
                            text: opmlFeed.title
//                            selected: false
                            visible: !liStandardRoot.isHidden
//                            height: visible ? units.gu(6) : 0

                            property var opmlFeed: liStandardRoot.opmlRoot == undefined ?
                                undefined : liStandardRoot.opmlRoot.children[index]

                            Connections {
                                target: liStandardRoot
                                onIsCheckedChanged: {
                                    if (liStandardRoot.isChecked) {
                                        listitemFeed.selected = true
                                        checkBoxFeed.checked = true
                                        listitemFeed.opmlFeed.isSelected = true
                                    }
                                    else {
                                        listitemFeed.selected = false
                                        checkBoxFeed.checked = false
                                        listitemFeed.opmlFeed.isSelected = false
                                    }
                                }
                            }

                            CheckBox{
                                id: checkBoxFeed
                                anchors
                                {
                                    right: parent.right; rightMargin: units.gu(5)
                                    verticalCenter: parent.verticalCenter
                                }
                                enabled: liStandardRoot.isChecked
//                                checked: parent.opmlFeed.isSelected

                                MouseArea { anchors.fill: parent; onClicked: {} }
                            }

                            Rectangle {
                                anchors.fill: parent
                                color: "#55000000"
                                visible: !liStandardRoot.isChecked
                            }

                            onClicked:
                            {
//                                importFeeds.test()
                                if (liStandardRoot.isChecked) {
                                    selected = !selected
                                    //                                console.log("xmlUrl: ", opmlFeed.xmlUrl /*JSON.stringify(opmlRoot)*/)
                                    listitemFeed.opmlFeed.isSelected = !listitemFeed.opmlFeed.isSelected
                                    checkBoxFeed.checked = listitemFeed.opmlFeed.isSelected
                                }
                            }
                        }
                    }
                }
            } //repeaterFeedList
        }

    }
    /////////////////////////////////////////////////////////////////////   opml content    end here

    /////////////////////////////////////////////////////////////////////   import tips    start here
    Label {
        visible: repeaterFeedList.opmlList == undefined
        anchors { left: parent.left; right: parent.right; margins: units.gu(3) }
        anchors { top: parent.top; topMargin: units.gu(6) }
//        horizontalAlignment: Text.AlignHCenter
        wrapMode: Text.WrapAtWordBoundaryOrAnywhere
        text: i18n.tr("Attention please, before importing opml file, Shorts only support one opml structure. <br><br>
For example: <br><br>Folder0<br>  ---feed0<br>  ---feed1<br>Folder1<br>  ---feed3<br>  ---feed4")
    }

    Column {
//        width: childrenRect.width
//        height: childrenRect.height
        anchors.centerIn: parent
        spacing: units.gu(1)
        visible: repeaterFeedList.opmlList == undefined

        Label {
            text: i18n.tr("Please select an opml file")
        }

        Button {
            anchors.horizontalCenter: parent.horizontalCenter
            text: i18n.tr("Open")

            onClicked: {
                pageStack.push(contentPickerDialog)
            }
        }
    }
    /////////////////////////////////////////////////////////////////////   import tips    end here

    //////////////////////////////////////////////////////////////////         Opml Parser
    OpmlParser {
        id: opmlParser
        opmlPath: ""

        onParseFinished: {
            repeaterFeedList.addOpmlObjs(opml)
        }
    }
}
