import QtQuick 2.4
import Ubuntu.Components 1.3
import UserMetrics 0.1
import com.canonical.Oxide 1.5 as Oxide
import Dekko.Models 0.2
import Dekko.Settings 0.2
import Dekko.Theme 0.2
import "../Components"

Page {
    id: oneMessagePage

    property bool showBack: false
    MessageHeader {
        id: envelopeHeader
        showBack: dekko.viewState.isSmallFF
    }

    anchors.fill: parent
    // Our singleThreadModel by default is in descending order as it is
    // actually just a a flattened subtree model of the msglistmodel
    // So to display it properly we have to switch it here to display
    // newest at the bottom
    SortFilterModel {
        id: sortedThread
        model: dekko.currentAccount.singleThreadModel
        sort.property: "date"
        sort.order: Qt.AscendingOrder
        sortCaseSensitivity: Qt.CaseInsensitive
    }

    MessageModel {
        id: msgModel
        imapModel: dekko.currentAccount.imapModel
        mailbox: dekko.currentAccount.msgListModel ? dekko.currentAccount.msgListModel.mailboxName : ""
        accountId: dekko.currentAccount.accountId
        accountIds: dekko.accountsManager.accountIds // needed for sender identity lookups
        preferPlainText: GlobalSettings.preferences.preferPlainText
        onMainPartUrlChanged: {
            console.log("MAIN PART URL: ", mainPartUrl)
            wv.currentZoomLevel = 100;
            startMarkAsReadTimerPerSetting()
            interestingUrlToLoad = mainPartUrl;
            wv.interestingIsHtml = mainPartIsHtml;
            wv.url = interestingUrlToLoad
            attachmentsPanel.visible = Qt.binding(function(){
                return (msgModel.hasValidIndex && !attachments.isEmpty())
            })
        }
        onMessageChanged: {
            if (hasValidIndex) {
                wv.setCidQuery(uid)
            }
        }
    }

    Connections {
        target: dekko.currentAccount.singleThreadModel
        onThreadRootChanged: {
            detailsPanel.showDetails = false
            wv.url = "about:blank"
            msgModel.messageClosed()
            msgModel.setMessage(dekko.currentAccount.singleThreadModel.threadRootIndex)
        }
    }

    Connections {
        target: dekko
        onCurrentAccountChanged: {
            detailsPanel.showDetails = false
            if (dekko.currentAccount.singleThreadModel.hasValidIndex) {
                msgModel.setMessage(dekko.currentAccount.singleThreadModel.threadRootIndex)
            } else {
                msgModel.messageClosed()
                wv.url = "about:blank"
            }
        }
    }

    property url interestingUrlToLoad

    function startMarkAsReadTimerPerSetting() {
        switch (GlobalSettings.preferences.markAsRead) {
        case Preferences.NEVER:
            break;
        case Preferences.AFTER_X_SECS:
            markAsReadTimer.interval = GlobalSettings.preferences.markAsReadAfter * 1000
            markAsReadTimer.start()
            break;
        case Preferences.IMMEDIATELY:
            markAsReadTimer.start()
            break;
        }
    }

    Timer {
        id: markAsReadTimer
        repeat: false
        interval: 50
        onTriggered: {
            msgModel.markMessageRead(true);
            if (dekko.currentAccount.isGmail) {
                console.log("Starting gmail hack to double mark \Seen")
                gmailHack.start()
            }
            clicksMetric.increment()
        }
    }

    Timer {
        id: gmailHack
        repeat: false
        interval: 500
        onTriggered: dekko.currentAccount.msgModel.markMessageRead(true);
    }
    Metric {
        id: clicksMetric
        name: "email-read-count"
        format: "<b>%1</b> " + qsTr("e-mails read today")
        emptyFormat: qsTr("No e-mails read today")
        domain: "dekko.dekkoproject"
    }

    Action {
        id: zoomAction
        parameterType: Action.Integer
        onTriggered: {
            wv.currentZoomLevel = value
            wv.zoom(value)
        }
    }

    Action {
        id: viewSourceAction
        onTriggered: {
            rootPageStack.push(Qt.resolvedUrl("MessageSourceViewer.qml"),
                               {
                                   messageIndex: msgModel.messageIndex
                               })
            console.log("VIEW SOURCE CLICKED")
        }
    }

    Action {
        id: viewFullScreen
        onTriggered: {
            rootPageStack.push(Qt.resolvedUrl("FullScreenViewer.qml"),
                               {
                                   pageTitle: msgModel.subject,
                                   messageUrl: interestingUrlToLoad
                               })
        }
    }

    Item {
        id: display
        clip: true
        visible: msgModel.hasValidIndex
        anchors {
            top: envelopeHeader.bottom
            left: parent.left
            right: parent.right
            bottom: hiddenMargin.top
        }

        DekkoWebView {
            id: wv
            anchors {
                fill: parent
                leftMargin: units.gu(1)
            }
            url: "about:blank"
            property int currentZoomLevel: 100
            locationBarController.mode: Oxide.LocationBarController.ModeAuto
            locationBarController.height: h.height
        }
        ThreadMessageHeader {
            id: h
            detailsVisible: detailsPanel.showDetails
            width: parent.width
            y: wv ? wv.locationBarController.offset : 0
            onShowDetails: detailsPanel.showDetails = !detailsPanel.showDetails
        }

        DetailsPanel {
            id: detailsPanel
            msgModel: msgModel
            anchors {
                left: parent.left
                right: parent.right
                top: h.bottom
            }
        }

        Rectangle {
            id: btmshadow
            anchors {
                left: parent.left
                right: parent.right
                top: h.bottom
            }
            opacity: wv.contentY > 10 ? 0.8 : 0.0
            Behavior on opacity {
                UbuntuNumberAnimation{}
            }

            height: units.gu(0.8)
            gradient: Gradient {
                GradientStop { position: 0.0; color: UbuntuColors.warmGrey }
                GradientStop { position: 1.0; color: "transparent" }
            }
        }
    }

    Item {
        id: hiddenMargin
        anchors {
            left: parent.left
            bottom: parent.bottom
            right: parent.right
        }
        height: attachmentsPanel.collapsedHeight
    }

    AttachmentsPanel {
        id: attachmentsPanel
        anchors {
            left: parent.left
            bottom: parent.bottom
            right: parent.right
        }
        maxHeight: display.height - units.gu(2)
        visible: msgModel.hasValidIndex && !msgModel.attachments.isEmpty()
    }
}
