/* 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 QtQml.StateMachine 1.0 as DSM

DSM.State {
    id: oaState
    initialState: wizard.oaId === 0 ? createNewOnlineAccount : aquireDetails

    signal success()
    signal back()

    property alias nextTargetState: nextTargetTransition.targetState
    property alias backTargetState: backTargetTransition.targetState

    DSM.State {
        id: aquireDetails
        signal success()
        property var overlay: undefined
        onEntered: {
            var c = Qt.createComponent(Qt.resolvedUrl("OnlineAccountsOverlay.qml"))
            console.log("CREATING OA OVERLAY")
            overlay = c.createObject(wizard)
            overlay.success.connect(success)
            // We have to explicitly call start() here, mainly because
            // if an account was enabled while the app was closed, on app start the
            // logic inside this component completes before the success signal is conected.
            overlay.start()
        }
        onExited: {
            overlay.destroy()
        }
        DSM.SignalTransition {
            id: successTransition
            signal: aquireDetails.success
            onTriggered: oaState.success()
        }

    }

    DSM.State {
        id: createNewOnlineAccount
        signal success()
        signal failed()
        property var setupItem: undefined
        onEntered: {
            wizard.oaCreatedLocally = true
            var c = Qt.createComponent(Qt.resolvedUrl("OnlineAccountSetup.qml"))
            setupItem = c.createObject(wizard)
            setupItem.successAquiringUoaId.connect(success)
        }
        onExited: {
            setupItem.destroy()
        }

        DSM.SignalTransition {
            signal: createNewOnlineAccount.success
            targetState: aquireDetails
        }
    }

    DSM.SignalTransition {
        id: nextTargetTransition
        signal: oaState.success
    }

    DSM.SignalTransition {
        id: backTargetTransition
        signal: oasState.back
    }
}
