/* 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.Popups 1.0
import UserMetrics 0.1
import Dekko.Theme 0.2
import Dekko.Composition 0.2
import "../Composer"
import "../Dialogs"
import "../Components"

Page {
    id: composePage

    property alias replyMode: composer.replyMode
    property alias replyPart: composer.replyPart
    property alias mailToUrl: composer.mailTo
    property string pageTitle: qsTr("Message")
    property bool isOpen
    property bool isBottomEdgeMode: false
    readonly property bool hasImapModel: dekko.currentAccount && dekko.currentAccount.imapModel

    signal close()

    function addAttachment(url) {
        console.log("[ComposePage::addAttachment] [INFO] passing url to composer: ", url)
        composer.addAttachmentUrl(url)
    }

    function appendTextToBody(text) {
        console.log("[ComposePage::appendTextToBody] [INFO] passing text to composer: ", text)
        composer.appendTextToBody(text)
    }

    flickable: null
    anchors.fill: parent

    onIsOpenChanged: {
        console.log("[ComposePage::isOpenChanged] [STATUS] composer page is open: ", isOpen)
        if (isOpen) {
            console.log("[ComposePage::isOpenChanged] [STATUS] Updating contacthint model")
            updateContactHintModel();
        }
    }

    function updateContactHintModel() {
        flattenContactModel.update();
        flattenRecentContactModel.update();
        console.log("[ComposePage::updateContactHintModel] [STATUS] Contact hint model updated! ")
    }
    function closeBottomEdge() {
        console.log("[ComposePage::closeBottomEdge] [STATUS] Closing bottom edge! ")
        if (!isBottomEdgeMode) {
            console.log("[ComposePage::closeBottomEdge] [STATUS] Popping page off stack ")
            rootPageStack.pop()
        } else {
            console.log("[ComposePage::closeBottomEdge] [STATUS] Restting composer ")
            replyMode = ReplyMode.REPLY_NONE
            composer.reset()
            console.log("[ComposePage::closeBottomEdge] [STATUS] Collapsing to bottom edge ")
            close()
        }
    }

    DekkoHeader {
        id: header
        title: pageTitle
        backAction: closeAction
        primaryAction: hasImapModel ? sendAction : null
//        secondaryActions: draftsAction
        extend: !dekko.viewState.isSmallFF && isBottomEdgeMode
    }


    Composer {
        id: composer
        anchors {
            left: parent.left
            top: header.bottom
            right: parent.right
            bottom: parent.bottom
        }
        isOpen: composePage.isOpen
        onSubmissionStarted: {
            console.log("[ComposePage::submissionStarted] [STATUS] Opening submission status dialog")
            PopupUtils.open(statusDialog)
        }
    }


    Action {
        id: draftsAction
        text: qsTr("Drafts")
        onTriggered: {
            draftsPanel.composer = true
            draftsPanel.open()
        }
        iconName: "edit"
    }

    Action {
        id: sendAction
        text: qsTr("Send")
        enabled: (hasImapModel && dekko.currentAccount.imapModel.isNetworkOnline)
        onTriggered: {
            console.log("[ComposePage::sendActionTriggered] [STATUS] Updating recipients")
            composer.updateRecipients()
            Qt.inputMethod.hide()
            console.log("[ComposePage::sendActionTriggered] [STATUS] Triggering msgComposer.send()")
            composer.msgComposer.send()
        }
        iconSource: Qt.resolvedUrl("qrc:///actions/send.svg")
    }

    Action {
        id: closeAction
        text: qsTr("Cancel")
        onTriggered: {
            Qt.inputMethod.hide()
            console.log("[ComposePage::closeActionTriggered] [STATUS] Closing composer.....")
            closePanelTimer.start()
            //            if (draftsPanel.opened) {
            //                draftsPanel.close()
            //            } else {

            //                Qt.inputMethod.hide()
            //                composer.loseFocus();
            //                //TODO: FIXME: only saving drafts for new messages atm
            //                if (composer.messageStarted) {
            //                    PopupUtils.open(draftsDialog, dekko, {isEditingDraft: composer.docId})
            //                } else {
            //                    closePanelTimer.start()
            //                }
            //            }
        }
        iconName: !isBottomEdgeMode ? "back" : "down"
    }

    Metric {
        id: clicksMetric
        name: "dekko-email-sent-count"
        format: "<b>%1</b> " + qsTr("e-mails sent today")
        emptyFormat: qsTr("No e-mails sent today")
        domain: "dekko.dekkoproject"
    }

    Component {
        id: statusDialog
        SubmissionStatusDialog {
            id: submissionStatusDialog
            msgComposer: composer.msgComposer
            onCloseClicked: {
                if (succeeded) {
                    succeeded = false
                    clicksMetric.increment()
                }
                PopupUtils.close(submissionStatusDialog)
                closePanelTimer.start()
            }
        }
    }

    Timer {
        id: closePanelTimer
        interval: 500
        onTriggered: closeBottomEdge();
    }
}
