/* 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.Utils 0.2

ProcessingOverlay {
    id: credentialValidation
    objectName: "credentialValidation"

    signal failedWithErrorMessage(string message)

    state: "running"
    states: [
        State {
            name: "running"
            PropertyChanges {
                target: credentialValidation
                text: qsTr("Validating credentials...")
            }
        },
        State {
            name: "complete"
            PropertyChanges {
                target: credentialValidation
                text: qsTr("All done!")
            }
            StateChangeScript {
                name: "startSuccessTimer"
                script: successTimer.start()
            }
        },
        State {
            name: "failed"
            PropertyChanges {
                target: credentialValidation
                text: qsTr("Authentication failed")
            }
            StateChangeScript {
                name: "startFailedTimer"
                script: failedTimer.start()
            }
        }

    ]

    readonly property bool isRunning: state === "running"

    ImapSettingVerifier {
        id: settingsVerifier
        username: wizard.account.imapSettings.username
        password: wizard.tempPasswordStore
        _imapSettings: wizard.account.imapSettings
        onResultChanged: {
            switch (result) {
            case ImapSettingVerifier.IMAP_SETTINGS_CONNECT_SUCCEED:
                credentialValidation.state = "complete"
                break
            case ImapSettingVerifier.IMAP_SETTINGS_CONNECT_FAILED:
                credentialValidation.state = "failed"
                break;
            }
        }

        Component.onCompleted: start()
    }

    Timer {
        id: successTimer
        interval: 1000
        repeat: false
        onTriggered: success()
    }

    Timer {
        id: failedTimer
        interval: 1500
        repeat: false
        onTriggered: failedWithErrorMessage(settingsVerifier.errorMessage)
    }
}
