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

   This file is part of the dekko

   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 or any later version
   accepted by the membership of KDE e.V. (or its successor approved
   by the membership of KDE e.V.), which shall act as a proxy
   defined in Section 14 of version 3 of the license.

   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.1
import Dekko.Accounts 0.2
import Dekko.Composition 0.2
import "../Components"
import "./Recipients"
import "./Editor"
import "./Identities"
import "./Attachments"

Item {
    id: composePage
    property alias isOpen: msgComposer.isOpened
    property alias replyMode: msgComposer.replyMode
    property alias replyPart: msgComposer.replyPart
    property string mailTo
    property alias msgComposer: msgComposer

    signal submissionStarted()

    function reset() {
        console.log("[Composer::reset] [STATUS] Resetting composer")
        msgComposer.reset()
        attachments.collapse()
        toField.showCcBcc = false
    }

    function updateRecipients() {
        toField.checkForUncommitedRecipients()
        ccField.checkForUncommitedRecipients()
        bccField.checkForUncommitedRecipients()
    }

    function addAttachmentUrl(url) {
        msgComposer.attachments.addFileAttachment(url.toString().replace("file://", ""))
    }

    function addAttachmentsFromUrls(files) {
        for (var i in files) {
            if (isRunningOnMir)
                addAttachmentUrl(files[i].url);
            else
                addAttachmentUrl(files[i]);
        }
    }

    function appendTextToBody(text) {
        console.log("Appending text to body: ", text)
        msgComposer.appendTextToBody(text)
    }

    QtObject {
        id: internal

        function accountUsesUOA(accountObj) {
            var c = Qt.createComponent(Qt.resolvedUrl("../Utils/RequestAccessToken.qml"))
            var o = c.createObject(dekko, {accountId: accountObj.accountId, uoaId: accountObj.uoaAccountId})
            o.accessToken.connect(function (id, token) {msgComposer.submission.setAccessToken(id, token)})
        }

        function showError(type, error) {
            var dlg = PopupUtils.open(Qt.resolvedUrl("../Dialogs/InfoDialog.qml"),
                                      composePage,
                                      {
                                          title: qsTr("Error"),
                                          text: error
                                      })
            dlg.close.connect(function() {
                switch (type) {
                case MsgComposer.NO_ERROR:
                    // This is a good thing... honest!
                    break;
                case MsgComposer.NO_VALID_TO_RECIPIENTS:
                    toField.getInputFocus()
                    break;
                case MsgComposer.NO_IDENTITIES:
                    break;
                case MsgComposer.NO_IDENTITY_SELECTED:
                    break;
                case MsgComposer.NO_VALID_SUBJECT:
                    subjectField.getInputFocus()
                    break;
                }
            });
        }
    }

    // MsgComposer is the API to the submission backend.
    // It's properties formulate a complete message suitable for mail transport
    MsgComposer {
        id: msgComposer
        addressbook: dekko.addressbookModel
        body: messageField.textDocument
        subject: subjectField.text
        replyMode: ReplyMode.REPLY_NONE
        manager: dekko.accountsManager
        onAddressbookChanged: {
            console.log("MAILTO: ", composePage.mailTo)
            if (composePage.mailTo) {
                setMailto.start()
            }
        }
        onErrorChanged: {
            console.log("Error: ", error)
            console.log("errorString: ", errorString)
            internal.showError(error, errorString)
        }
        onSubmissionStarting: composePage.submissionStarted()
    }
    Timer {
        id: setMailto
        interval: 100
        repeat: false
        onTriggered: msgComposer.mailToUrl = composePage.mailTo
    }

    Connections {
        target: msgComposer.submission
        onPasswordRequested: pwdManager.requestPassword(msgComposer.identities.selectedAccountId, PasswordManager.SMTP)
        // use the password manager to determine the uoaAccountId for the token request.
        onTokenRequested: pwdManager.requestPassword(msgComposer.identities.selectedAccountId, PasswordManager.SMTP)
        onMessageBuildFailed: console.log("Message build failed")
        onFailed: console.log("Submission failed")
        onGotPassword: console.log("Password accepted")
    }

    PasswordManager {
        id: pwdManager
        accountsManager: dekko.accountsManager
        onPasswordNowAvailable: {
            msgComposer.submission.setPassword(passwordObject.password)
        }
        onAccountUsesOnlineAccounts: {
            var c = Qt.createComponent(Qt.resolvedUrl("../Utils/RequestAccessToken.qml"))
            var o = c.createObject(dekko, {accountId: accountObject.accountId, uoaId: accountObject.uoaAccountId})
            o.accessToken.connect(function (id, token) {msgComposer.submission.setToken(token)})
        }
        onError: console.log(message)
        onReadingFailed: console.log(message)
        onWritingFailed: console.log(message)
        onJobCountChanged: console.log("Number of running password jobs: " + jobsInProgress)
        onPasswordStored: console.log("Password stored for accountId: " + id)
    }

    ScrollView {
        anchors {
            left: parent.left
            top: parent.top
            right: parent.right
            bottom: attachments.top
        }

        Flickable {
            id: flicker
            anchors {
                fill: parent
            }
            clip: true
            contentHeight: content.height + units.gu(2)

            Column {
                id: content
                anchors {
                    left: parent.left
                    top: parent.top
                    right: parent.right
                }
                Column {
                    id: contentHeader
                    anchors {
                        left: parent.left
                        right: parent.right
                    }
                    IdentitySelector {
                        anchors {
                            left: parent.left
                            right: parent.right
                        }
                        model: msgComposer.identities
                        selectedIndex: msgComposer.identities.selectedIndex
                    }

                    TypedRecipientField {
                        id: toField
                        anchors {
                            left: parent.left
                            right: parent.right
                        }
                        model: msgComposer.recipients.model
                        recipientKind: Recipient.TO
                        Component.onCompleted: {
                            toField.addRecipient.connect(msgComposer.recipients.addRecipient)
                        }
                    }

                    TypedRecipientField {
                        id: ccField
                        anchors {
                            left: parent.left
                            right: parent.right
                        }
                        visible: toField.showCcBcc
                        model: msgComposer.recipients.model
                        recipientKind: Recipient.CC
                        filterRole: RecipientsFilterModel.FILTER_CC
                        Component.onCompleted: {
                            ccField.addRecipient.connect(msgComposer.recipients.addRecipient)
                        }
                    }

                    TypedRecipientField {
                        id: bccField
                        anchors {
                            left: parent.left
                            right: parent.right
                        }
                        visible: toField.showCcBcc
                        model: msgComposer.recipients.model
                        recipientKind: Recipient.BCC
                        filterRole: RecipientsFilterModel.FILTER_BCC
                        Component.onCompleted: {
                            bccField.addRecipient.connect(msgComposer.recipients.addRecipient)
                        }
                    }

                    SubjectField {
                        id: subjectField
                        anchors {
                            left: parent.left
                            right: parent.right
                        }
                        text: msgComposer.subject
                        label: qsTr("Subject")
                        placeholderText: qsTr("Enter subject")
                    }
                }

                MessageField {
                    id: messageField
                    anchors {
                        left: parent.left
                        right: parent.right
                        leftMargin: units.gu(1)
                        rightMargin: units.gu(1)
                    }
                    placeholderText: qsTr("Enter Message")
                    onKeyPressed: {
                        var targetY = -1;
                        var p = messageField.getRectPos().y
                        var positonOnScreen = p - (flicker.contentY - contentHeader.height);
                        if (positonOnScreen < 0) {
                            targetY = contentHeader.height + p;
                        } else if (positonOnScreen > flicker.height - units.gu(5)) {
                            targetY = contentHeader.height + p - (flicker.height - units.gu(5))
                        }

                        if (targetY >= 0 && targetY < flicker.contentHeight) {
                            flicker.contentY = targetY;
                        }
                        flicker.returnToBounds();
                    }

                    ActivityIndicator {
                        anchors.centerIn: parent
                        visible: msgComposer.fetchingPart
                        running: visible
                    }
                }
            }
        }
    }

    AttachmentsPanel {
        id: attachments
        model: msgComposer.attachments
        maxHeight: parent.height / 2
        anchors {
            left: parent.left
            right: parent.right
            bottom: parent.bottom
        }
        onAddAttachment: {
            if (isRunningOnMir) {
                var contentDialog = PopupUtils.open(Qt.resolvedUrl("../Dialogs/ContentPickerDialog.qml"), dekko, {
                                                        isExport: false
                                                    });
                contentDialog.filesImported.connect(addAttachmentsFromUrls);
            } else {
                var c = Qt.createComponent(Qt.resolvedUrl("../Dialogs/AddAttachmentsDialog.qml"))
                var fileDialog = c.createObject(dekko)
                fileDialog.accepted.connect(function() {
                    addAttachmentsFromUrls(fileDialog.fileUrls)
                    fileDialog.close()
                    fileDialog.destroy()
                })
            }
        }
    }
}

