import QtQuick 2.4
import Ubuntu.Components 1.3
import "../MailboxView"
import Dekko.Accounts 0.2
import Dekko.Models 0.2

Item {
    id: p
    signal mailboxSelected(string mboxName)
    property bool pickerOpened: false
    onMailboxSelected: {
        if (pickerOpened) {
            console.log("Mailbox selected: closing picker")
            pickerOpened = false
            rootPageStack.pop()
        }
    }

    property Account account
    property var picker
    function pick() {
        if (pickerOpened) {
            return;
        }

        console.log("Opening picker")
        picker = pickerPage.createObject(p.parent, { account: account });
        picker.mailboxSelected.connect(mailboxSelected);
        rootPageStack.push(picker);
        pickerOpened = true;
    }

    Component {
        id: pickerPage
        Item {
            anchors.fill: parent
            property Account account

            DekkoHeader {
                id: header
                title: qsTr("Select a mailbox")
                backAction: Action {
                    id: backAction
                    enabled: true
                    iconName: "back"
                    onTriggered: {
                        pickerOpened = false
                        rootPageStack.pop()
                    }
                }
                enableSearching: true
                onSearchActivated: {
                    searchFilterModel.queryString = searchString
                    searchFilterModel.invalidate()
                }
                onSearchCanceled: {
                    searchFilterModel.queryString = ""
                    searchFilterModel.invalidate()
                }
            }
            signal mailboxSelected(string mailbox)

            MailboxFilterModel {
                id: filterModel
                filterRole: MailboxFilterModel.FILTER_NONE
                sourceModel: account.mailboxModel
            }

            FlatteningProxyModel {
                id: flatModel
                sourceModel: filterModel
            }
            MailboxFilterModel {
                id: searchFilterModel
                sourceModel: header.isSearchMode ? flatModel : null
                filterRole: MailboxFilterModel.FILTER_QUERY
            }
            MailboxListView {
                id: mboxListView
                property bool isSearchMode: header.isSearchMode
                isPickMode: true
                lockDelegate: true
                anchors.fill: parent
                anchors.topMargin: units.gu(7)
                model: header.isSearchMode ? searchFilterModel : flatModel
                onOpenMailbox: {
                    mailboxSelected(mboxName)
                }
            }
        }
    }
}
