/* Copyright (C) 2014-2016 Dan Chapman <dpniel@ubuntu.com>

   This file is part of Dekko email client for Ubuntu Devices/

   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 2 of
   the License or (at your option) 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.0 as ListItem
import Ubuntu.Components.Popups 1.1
import DekkoCore 0.2
import UserMetrics 0.1
import "../Utils/Utils.js" as Utils
import "../Contact/imports"
import "../Components"


Item {
    id: delegate

    readonly property bool expanded: state === "expanded"
    readonly property bool threadingEnabled: GlobalSettings.developer.enableThreading
    property url interestingUrlToLoad: ""
    readonly property bool interestingUrlAvailable: interestingUrlToLoad

    height: units.gu(10)
    width: parent.width

    state: threadingEnabled ? "collapsed" : "expanded"
    states: [
        State {
            name: "collapsed"
            PropertyChanges {
                target:delegate
                height: units.gu(10)
            }
            PropertyChanges {
                target: oxideWrapper
                height: units.gu(7)
            }
            // Reset oxide view
            PropertyChanges {
                target: wv
                url: "about:blank"
                visible: false
                finalHeight: 0
                ch: 0
            }
        },
        State {
            name: "expanded"
            PropertyChanges {
                target: wv
                url: interestingUrlToLoad
                visible: true
            }
            StateChangeScript {
                name: "buildMessage"
                script: buildMessageIfNotAlready()
            }
        }
    ]

    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;
        }
    }

    function buildMessageIfNotAlready() {
        if (!interestingUrlAvailable) {
            messageBuilder.messageModel = msgModel
            messageBuilder.buildMessage()
        }
    }

    MessageModel {
        id: msgModel
        imapModel: dekko.currentAccount.imapModel
        mailbox: dekko.currentAccount.msgListModel.mailboxName
        accountId: dekko.currentAccount.accountId
        preferPlainText: GlobalSettings.preferences.preferPlainText
        onMainPartUrlChanged: {
            console.log("MAIN PART URL: ", mainPartUrl)
            wv.currentZoomLevel = 100;
            startMarkAsReadTimerPerSetting()
            interestingUrlToLoad = mainPartUrl;
            wv.interestingIsHtml = mainPartIsHtml;
            wv.url = interestingUrlToLoad
        }
        onMessageChanged: {
            if (hasValidIndex) {
                wv.setCidQuery(uid)
            }
        }
    }

    Behavior on height {
        UbuntuNumberAnimation{ duration: UbuntuAnimation.SnapDuration }
    }

    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
                               })
        }
    }

    Column {
        id: col
        anchors {
            left: parent.left
            top: parent.top
            right: parent.right
        }
        visible: dekko.currentAccount.singleThreadModel.hasValidIndex

        ThreadMessageHeader {
            id: header
            anchors {
                left: parent.left
                right: parent.right
            }
            onClicked: delegate.state = "expanded"
        }


        Item {
            id: oxideWrapper
            focus: true
            visible: true
            anchors {
                left: parent.left
                leftMargin: units.gu(1)
                right: parent.right
                rightMargin:units.gu(1)
            }
            // The webview won't load anything if height is 0 when collapsed
            // But we need to drive the new height based on the contentHeight
            // of the message.
            height: units.gu(7)

            DekkoWebView {
                id: wv
                objectName: "OxideWebView"
                parent: oxideWrapper
                focus: false
                function reset() {
                    ch = 0
                    finalHeight = 0
                    oxideWrapper.height = 0
                }
//                onLoadProgressChanged: if (loadProgress === 100) oxideWrapper.visible = true

                onWidthChanged: resizeView()
                anchors.fill: parent
                property int currentZoomLevel: 100
                property int ch: 0
                property int finalHeight: 0
                onContentHeightChanged: {

                    if (!delegate.expanded) {
                        return
                    }
                    if (viewportHeight === contentHeight) {
                        return
                    }
                    // FIXME: handle content height decreasing
                    if (finalHeight === 0) {
                        resizeView()
                    } else if (height > units.gu(7) && finalHeight === 0) {
                        ch = contentHeight
                        finalHeight = ch
                        delegate.height = finalHeight + header.height
                    }
                }

                function resizeView() {
                    if (!delegate.expanded) {
                        return
                    }
                    ch = contentHeight
                    oxideWrapper.height = ch
                    // FIXME: col.height seems to lie here and not include
                    // the height of the webview.
                    delegate.height = oxideWrapper.height + header.height
                }


                Timer {
                    id: delayLoad
                    interval: 50
                    repeat: false
                    onTriggered: {
                        if (!model.isMarkedRead || model.index === dekko.currentAccount.singleThreadModel.firstInterestingIndex) {
                            delegate.state = "expanded"
                            if (model.index === dekko.currentAccount.singleThreadModel.firstInterestingIndex) {
                                delayPosition.start()
                            }
                        }
                    }
                }
                Timer {
                    id: delayPosition
                    interval: 500
                    repeat: false
                    onTriggered: list.positionViewAtIndex(dekko.currentAccount.singleThreadModel.firstInterestingIndex, ListView.Contain)
                }

                OxideOverlay {
                    id: wrapper2
                    anchors.fill: parent
                    listView: list
                }
            }
        }
    }
    ListItem.ThinDivider {
        id: divider
        visible: threadingEnabled
        anchors {
            left: parent.left
            right: parent.right
            bottom: parent.bottom
        }
    }
}
