/* 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 Dekko.Accounts 0.2
import Dekko.Models 0.2
import Dekko.Settings 0.2
import Ubuntu.Components 1.3
import Ubuntu.Components.Popups 1.0
import Ubuntu.OnlineAccounts 0.1 as OA

ProcessingOverlay {
    id: autoConfigOverlay

    text: qsTr("New account detected")

    onSuccess: console.log("SUCCESS CALLED")

    signal start()
    onStart: timer.start()

    Timer {
        id: timer
        interval: 1000
        repeat: false
        onTriggered: internal.loadAccount()
    }
    // This leaves enough time for the ConfirmationDialog to be destroyed before
    // overlay.destroy() get's called on state exit.
    Timer {
        id: emitSuccess
        interval: 1000
        repeat: false
        onTriggered: success()
    }

    Timer {
        id: cancelSetup
        interval: 250
        onTriggered: {
            rootPageStack.pop()
            dekko.setupWizardRunning = false
        }
    }

    Action {
        id: confirmAction
        onTriggered: internal.commitAccountDetails()
    }

    Action {
        id: cancelAction
        onTriggered: {
            account.updateEnabled(false)
            cancelSetup.start()
        }
    }

    QtObject {
        id: internal

        function determineConnectionMethods(conType, selectedPreset) {
            if (conType === "imap") {
                if (selectedPreset.imapSSL) {
                    return ImapSettings.SSL
                } else if (selectedPreset.imapStartTls) {
                    return ImapSettings.STARTTLS
                } else {
                    return ImapSettings.NONE
                }
            } else if (conType === "smtp") {
                if (selectedPreset.smtpSSL) {
                    return SmtpSettings.SSMTP;
                } else if (selectedPreset.smtpStartTls) {
                    return SmtpSettings.SMTP_STARTTLS;
                } else {
                    return SmtpSettings.SMTP;
                }
            } else {
                console.log("Cannot determine connection for unknown type: " + conType);
            }
        }

        function loadAccount() {
            console.log("LOADING ACCOUNT")
            account.objectHandle = OA.Manager.loadAccount(wizard.oaId)
        }

        function confirmUseAccount() {
            if (wizard.oaCreatedLocally) {
                internal.commitAccountDetails()
                wizard.accountType = NewAccountType.ONLINE_ACCOUNT
            } else {
                PopupUtils.open(Qt.resolvedUrl("../Dialogs/ConfirmationDialog.qml"), wizard, {
                                confirmAction: confirmAction,
                                cancelAction: cancelAction,
                                title: qsTr("New account"),
                                text: qsTr("%1 account found for %2.\n\nWould you like to configure this now?").arg(account.provider.displayName).arg(account.displayName)
                            })
            }
        }

        function commitAccountDetails() {
            text = qsTr("Collecting details")
            if (account.provider.displayName === "Google") {
                wizard.account.uoaSettings.provider = UOASettings.GMAIL
                wizard.account.uoaSettings.enabled = account.enabled
                wizard.account.uoaSettings.uoaAccountId = account.accountId
                wizard.account.imapSettings.username = account.displayName
                wizard.account.smtpSettings.username = account.displayName
                createGmailDefaults()
                emitSuccess.start()
            } else {
                // We don't support anything but google atm, so disable it.
                cancelAction.trigger()
            }
        }

        function createGmailDefaults() {
            var config = presetModel.getPresetConfigByName("gmail");
            wizard.account.imapSettings.server = config.imapServer
            wizard.account.imapSettings.port = config.imapPort
            wizard.account.imapSettings.connectionMethod = determineConnectionMethods("imap", config)
            wizard.account.imapSettings.authenticationMethod = ImapSettings.OAUTH
            wizard.account.smtpSettings.server = config.smtpServer
            wizard.account.smtpSettings.port = config.smtpPort
            wizard.account.smtpSettings.submissionMethod = determineConnectionMethods("smtp", config)
            wizard.account.smtpSettings.authenticationMethod = SmtpSettings.OAUTH
        }
    }

    PreSetProvidersModel {
        id: presetModel
    }

    OA.Account {
        id: account
        onAccountIdChanged: {
            if (accountId > 0 && provider.displayName === "Google") {
                internal.confirmUseAccount()
            }
        }
    }
}
