import QtQuick 2.4
import Ubuntu.Components 1.3
import Ubuntu.Components.ListItems 1.3 as ListItem
import Ubuntu.Components.Popups 1.3

import "./pages"
import "./tabs"
import "./components"
import "./utils/databasemodule_v2.js" as DB

import "./nongoogle"

MainView {
    id: mainView

    property bool isTabletMode: false // Disabled for now.
//    property bool isTabletMode: {
//        if (width === 0 || height === 0)
//            return
//        return (width > units.gu(90))
//    }

    objectName: "mainView"
    applicationName: "com.ubuntu.shorts"
    anchorToKeyboard: true

    width: units.gu(100)
    height: units.gu(84)
    focus: true

    backgroundColor: "#F5F5F5"

    Component.onCompleted: {

        var dbParams = {"isRefreshRequired" : false,
            "oldDbVersion" : optionsKeeper.dbVersion(),
            "newDbVersion" : ""
        }

        DB.adjustDb(dbParams)

        if (dbParams.oldDbVersion != dbParams.newDbVersion)
            optionsKeeper.setDbVersion(dbParams.newDbVersion)


        if (dbParams.isRefreshRequired) {
            topicManagement.reloadTopics()
            refresh()
        } else {
            repeater.reloadTabs()
            /* If "isListView" is set "reloadTab" will be called automatically. */
            if (!pageStack.isListView) {
                shortsTab.reloadTab()
                savedTab.reloadTab()
            }
        }
    }

    /* Refresh current topic or all feeds if we are in the Shorts.
     */
    function refresh() {
        var topicId = 0
        if (pageStack.currentPage == tabstabs) {
            var curTab = tabstabs.selectedTab
            topicId = curTab.topicId
        }

        console.log("REFRESH TOPIC", topicId)
        if (topicId == -2) {
            refreshSavedTab()
            return
        }

        var feeds = topicId ? DB.loadFeedsFromTag(topicId) : DB.loadFeeds()

        var feedarray = []
        for (var i=0; i< feeds.rows.length; i++) {
            feedarray.push(feeds.rows.item(i))
        }
        networkManager.updateFeeds(feedarray, topicId)
    }

    function reloadViews(topicId) {
        // savedTab.reload() // Doesn't change with network update.
        topicId = topicId || 0

        shortsTab.reloadTab()
        if (topicId == 0 || !repeater.containsTopic(topicId))
            repeater.reloadTabs()

        tabstabs.selectTopic(topicId)
    }

    // refresh "Saved" Tab
    function refreshSavedTab() {
        savedTab.reloadTab()
    }

    function showArticle(model, index) {      //   go to single article page
        articlePage.setFeed(model, index)
        pageStack.push(articlePage)
    }

    function editFeed(feedid, title, url, pTopicId) {
        editFeed.setValues(feedid, title, url, pTopicId) ;
        pageStack.push(editFeed) ;
    }

    //  change the topic name if the name changed by management
    function changeTopicName(topicId, newName) {
        repeater.changeTopicName(topicId, newName)
    }

    /* -------------------------- Visuals ---------------------------- */

    PageStack {
        id: pageStack
        objectName: "pageStack"

        property bool isListView: optionsKeeper.useListMode
        property var commonHeadActions: [refreshAction, changeModeAction, editTopicsAction, nightModeAction, actionSetting]

        anchors.fill: parent
        focus: true

        Component.onCompleted: {
            push(tabstabs)
        }

        Keys.onPressed: {
            console.log(objectName, event.key.toString(16), event.modifiers.toString(16))

            /* Hotkeys for tabs management.
             */
            if (currentPage == tabstabs) {
                if (event.key >= Qt.Key_0 && event.key <= Qt.Key_9 &&
                        event.modifiers & Qt.AltModifier) { // Digits for switching tabs...
                    var tabNumber = event.key - Qt.Key_0
                    if (tabNumber < tabstabs.getTabCount()) {
                        tabstabs.selectedTabIndex = tabNumber
                        event.accepted = true
                    }
                }

                // Refresh on F5.
                if (event.key === Qt.Key_F5)
                    refresh()

                if (event.modifiers & Qt.ControlModifier) { // Control+Tab and Control+Shift+Tab
                    if (event.key === Qt.Key_Backtab) {
                        tabstabs.selectedTabIndex = (tabstabs.selectedTabIndex - 1 + tabstabs.getTabCount()) % tabstabs.getTabCount()
                        event.accepted = true
                    } else if (event.key === Qt.Key_Tab) {
                        tabstabs.selectedTabIndex = (tabstabs.selectedTabIndex + 1) % tabstabs.getTabCount()
                        event.accepted = true
                    } else if (event.key === Qt.Key_N) {
                        pageStack.push(appendFeedPage, {"isDirty" : true})
                    } else if (event.key === Qt.Key_R) {
                        refresh()
                    }
                }
            } else if (currentPage == articlePage) {
                if (event.key == Qt.Key_Left) {
                    articlePage.articleView.showPrevArticle()
                } else if (event.key == Qt.Key_Right) {
                    articlePage.articleView.showNextArticle()
                }
            }
        }

        onCurrentPageChanged: {
            if (currentPage != null) {
                if (currentPage.reloadPageContent)
                    currentPage.reloadPageContent()
            }
        }

        /* -------------------------- Actions ---------------------------- */

        Action {
            id: refreshAction

            text:  i18n.tr("Refresh")
            iconName: "reload"
            onTriggered: refresh()
        }

        Action {
            id: changeModeAction
            text:  pageStack.isListView ? i18n.tr("Grid View") : i18n.tr("List view")
            iconName: pageStack.isListView ? "view-grid-symbolic" : "view-list-symbolic"
            onTriggered: {
                pageStack.isListView = !pageStack.isListView
                optionsKeeper.setUseListMode(pageStack.isListView)


                /* Spike solution for bug: https://bugs.launchpad.net/ubuntu-rssreader-app/+bug/1214916
                                 * If we switched to grid, manually cause header return.
                                 */
                if (!pageStack.isListView) {
                    var ind = tabstabs.selectedTabIndex
                    if (ind == 0) {
                        tabstabs.selectedTabIndex = 1
                        tabstabs.selectedTabIndex = ind
                    } else {
                        tabstabs.selectedTabIndex = 0
                        tabstabs.selectedTabIndex = ind
                    }
                }
            } // onTriggered
        }

        Action {
            id: editTopicsAction
            objectName:"editTopicsAction"
            text:  i18n.tr("Edit topics")
            iconName: "edit"
            onTriggered: {
                pageStack.push(topicManagement)
            }
        }

        Action {
            id: nightModeAction
            objectName:"nightModeAction"
            text: optionsKeeper.useDarkTheme ? i18n.tr("Disable night mode") : i18n.tr("Enable night mode")
            iconName: "night-mode"
            onTriggered: {
                optionsKeeper.useDarkTheme = !optionsKeeper.useDarkTheme
            }
        }

        Action {
            id: actionSetting
            objectName:"actionSetting"
            text:  i18n.tr("Settings")
            iconName: "settings"
            onTriggered: {
                pageStack.push(Qt.resolvedUrl("./pages/PageSettings.qml"))
            }
        }

        /* -------------------------- Pages & Tabs ---------------------------- */

        BottomEdgeTabs {
            id: tabstabs

            objectName: "tabstabs"
            visible: false

            bottomEdgePage: optionsKeeper.useGoogleSearch ? appendFeedPage : appendNGFeedPage
            bottomEdgeTitle: i18n.tr("Add feeds")
            bottomEdgeBackgroundColor: "#F5F5F5" // "#875864"
            bottomEdgeTipColor: "#5533b5e5"// "#E0E0E0" //"#9b616c"

            Component.onCompleted: {
                selectedTabIndex = 1
            }

            onSelectedTabIndexChanged: {
                // console.log("onSelectedTabIndexChanged", selectedTabIndex)
                if (selectedTabIndex <= 1)
                    return
                repeater.reloadTabAt(selectedTabIndex - 2)
            }

            function getTabCount() {
                return repeater.model + 2 // + Shorts and Saved
            }

            function selectTopic(topicId) {
                if (/*topicId == undefined ||*/ topicId == 0 ) {
                    tabstabs.selectedTabIndex = 1
                } else {
                    for(var i = 0; i < repeater.count; i++) {
                        if (repeater.itemAt(i).topicId == topicId) {
                            repeater.reloadTabAt(i, "selectTopic")
                            tabstabs.selectedTabIndex = i + 2
                            break
                        }
                    }
                }
            }

            /* Used for keeping status in sync across tabs.
             */
            function updateStatusInModels(article, status) {
                var topicId = article.tagId
                var articleId = article.id

                savedTab.updateStatusInModel(articleId, status)
                shortsTab.updateStatusInModel(articleId, status)
                for(var i = 0; i < repeater.count; i++) {
                    if (repeater.itemAt(i).topicId == topicId) {
                        repeater.itemAt(i).updateStatusInModel(articleId, status)
                        break
                    }
                }
            }

            /* Used for keeping favourite in sync across tabs.
             */
            function updateFavouriteInModels(article, fav) {
                var topicId = article.tagId
                var articleId = article.id

                savedTab.updateFavouriteInModel(article, fav)
                shortsTab.updateFavouriteInModel(articleId, fav)
                for(var i = 0; i < repeater.count; i++) {
                    if (repeater.itemAt(i).topicId == topicId) {
                        repeater.itemAt(i).updateFavouriteInModel(articleId, fav)
                        return
                    }
                }
            }

            SavedTab {
                id: savedTab

                objectName: "Tab1"
                title: i18n.tr("Saved")
                topicId: -2
            }

            ShortsTab {
                id: shortsTab

                objectName: "Tab0"
                title: i18n.tr("Shorts")
                topicId: 0
            }

            Repeater {
                id: repeater

                TopicTab { }

                function reloadTabs() {
                    repeater.model = 0
                    var tags = DB.loadTags()
                    repeater.model = tags.rows.length

                    for (var i = 0; i< tags.rows.length; i++) {
                        repeater.itemAt(i).title = tags.rows.item(i).name
                        repeater.itemAt(i).topicId = tags.rows.item(i).id
                    }
                }

                function changeTopicName(topicId, newName) {
                    for(var i = 0; i < repeater.count; i++) {
                        if (repeater.itemAt(i).topicId == topicId) {
                            repeater.itemAt(i).title = newName
                            break
                        }
                    }
                }

                function reloadTabAt(tabIndex, purpose) {
                    if (tabIndex >= repeater.count)
                        return

                    repeater.itemAt(tabIndex).reloadTab(purpose)
                }

                function containsTopic(topicId) {
                    for(var i = 0; i < repeater.count; i++) {
                        if (repeater.itemAt(i).topicId == topicId) {
                            return true
                        }
                    }

                    return false
                }
            } // Repeater
        } // Tabs

        // ******************************** Create Topic **********************///////////////

        CreateTopicPage {
            id: createTopicPage
            visible: false
            flickable: null
        } // Page

        // ******************************** APPEND FEED ***********************///////////////

        AppendFeedPage {
            id: appendFeedPage

            title: i18n.tr("Add feeds")
            flickable: null
            visible: false
        }

        AppendNGFeedPage {
            id: appendNGFeedPage

            title: i18n.tr("Add feeds")
            flickable: null
            visible: false
        }
        // ******************************** Choose Topic Page ***********************///////////////

        ChooseTopicPage {
            id: chooseTopicPage
            visible: false
        }

        // ******************************** Rss Feed Page ***********************///////////////

        ArticleViewPage {
            id: articlePage
            visible: false

            Connections {
                target: articlePage.articleView

                onArticleStatusChanged: {
                    tabstabs.updateStatusInModels(article, status)
                }

                onArticleFavouriteChanged: {
                    tabstabs.updateFavouriteInModels(article, favourite)
                }
            }
        }

        // ******************************** Topic Management Page ***********************///////////////
        TopicManagement {
            id: topicManagement
            visible: false
        }

        // ******************************** Edit Feed Page ***********************///////////////
        EditFeedPage {
            id: editFeed
            visible: false
        }
    } // PageStack

    /* -------------------------- Utils ---------------------------- */

    NetworkManager {
        id: networkManager

        onDownloadFinished: {
            reloadViews(topicId)
        }

        onDownloadStarted: {
            PopupUtils.open(refreshWaitDialogComponent, null)
        }
    }

    OptionsKeeper {
        id: optionsKeeper
    }

    // Positioner to detect current position
    Positioner {
        id: positionDetector
    }

    /* -------------------------- Components ---------------------------- */

    Component {
        id: refreshWaitDialogComponent

        Dialog {
            id: refreshWaitDialog
            objectName: "refreshWaitDialog"

            title: i18n.tr("Checking for new articles")

            ActivityIndicator {
                objectName: "activityindicator"
                running: true
            }

            Button {
                text: i18n.tr("Cancel")
                objectName: "refreshCancel"
                color: UbuntuColors.orange
                onClicked: {
                    networkManager.cancelDownload()
                    PopupUtils.close(refreshWaitDialog)
                }
            }

            Connections {
                target: networkManager

                onDownloadFinished: {
                    PopupUtils.close(refreshWaitDialog)
                    if ( networkManager.operationStatus === "withErrors" ) {
                        PopupUtils.open(errorDialogComponent, appendFeedPage,
                                        {"text" : i18n.tr("Perhaps some of the channels have not been updated."),
                                            "title" : i18n.tr("Errors occurred during the update")})
                    }
                }
            }
        } // Dialog
    } // Component

    Component {
        id: errorDialogComponent

        Dialog {
            id: errorDialog

            Button {
                text: i18n.tr("Ok")
                objectName: "errordialogbutton"
                onClicked: PopupUtils.close(errorDialog)
            }
        }
    } // Component

    ////////////////////////////////////////////////////////  a dialog to ask user if she/he wants to turn off the google search
    Component {
        id: componentDialogNG

        Dialog {
            id: dialogNG
            title: i18n.tr("Warning")
            text: i18n.tr("Shorts detects that you're located in an area which blocks Google's IP.<br><br>"
                          + "We strongly reconmend you to turn off the Google search funtion."
                          + "Or you can do it in the settings page manually.")

            Button {
                text: i18n.tr("Yes, please.")
                color: UbuntuColors.orange
                objectName: "dialogNGButtonYes"
                onClicked: {
                    optionsKeeper.setUseGoogleSearch(false)
                    PopupUtils.close(dialogNG)
                }
            }

            Button {
                text: i18n.tr("No, thanks.")
                objectName: "dialogNGButtonNo"
                onClicked: PopupUtils.close(dialogNG)
            }
        }
    } // Component

    /* -------------------------- Connections ---------------------------- */

    Connections {
        target: createTopicPage

        onTopicAdded: {
            reloadViews()
        }
    }

    Connections {
        target: chooseTopicPage

        onTopicChoosen: {
            networkManager.updateFeeds(addedFeeds, topicId)
        }
    }

    Connections {
        target: topicManagement

        onFeedEdit: {
            console.log("onFeedEdit: ", topicId)
            shortsTab.reloadTab()
            tabstabs.selectTopic(topicId)
        }

        onTopicDeleted: {
            reloadViews()
        }
    }

    layer.effect: DarkModeShader {}
    layer.enabled: optionsKeeper.useDarkTheme //  && pageStack.currentPage == articlePage
}
