/* Copyright (C) 2015 Boren Zhang <bobo1993324@gmail.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 Ubuntu.Components 1.3
import Ubuntu.Components.Popups 1.0
import Ubuntu.Components.ListItems 1.0 as ListItem
import Dekko.Contacts 0.2
import Dekko.Theme 0.2
import "../Composer"
import "../Components"
import "imports"

Page {
    id: root

    property var currentContactModel: addressbookModelFiltered

    Component.onCompleted: {
        addressbookModelFiltered.sort();
        recentContactModelFiltered.sort();
    }

    Action {
        id: closeAction
        iconName: "back"
        onTriggered: {
            addressbookModelFiltered.filterRole = -1;
            internalStack.pop();
        }
    }

    Action {
        id: searchAction
        iconName: "search"
        onTriggered: {
            header.state = "custom"
        }
    }
    Action {
        id: newContactAction
        iconName: "contact-new"
        onTriggered: {
            var dialog = PopupUtils.open(Qt.resolvedUrl("./imports/AddContactDialog.qml"));
            dialog.enterDetailClicked.connect(function() {
                internalStack.push(Qt.resolvedUrl("./ContactEditPage.qml"));
            });
            dialog.fromAddressbookClicked.connect(function() {
                 contactImporter.requestContact();
            });
            dialog.fromVcard.connect(function() {
                console.log("FROM VCARD CLICKED")
                var c = Qt.createComponent(Qt.resolvedUrl("../Dialogs/AddAttachmentsDialog.qml"))
                var fileDialog = c.createObject(dekko, {
                                                    nameFilters: [ "VCard file (*.vcf *.vcard)" ],
                                                    selectMultiple: false,
                                                })
                fileDialog.accepted.connect(function() {
                    contactImporter.vCardParser.vCardUrl = fileDialog.fileUrl
                    fileDialog.close()
                    fileDialog.destroy()
                    })
            });
        }
    }
    Action {
        id: leaveSearchAction
        text: "cancel"
        iconName: "cancel"
        onTriggered: {
            currentContactModel.setFilterFixedString("");
            header.state = "default"
        }
    }
    Connections {
        target: addressbookModel
        onImportContactCompleted: {
            PopupUtils.open(
                    Qt.resolvedUrl("../Dialogs/DelayHideInfoDialog.qml"),
                    root, {
                        title: qsTr("%1 contacts imported.").arg(numImported)
                    }).hideIn(2);
        }
    }
    ContactImport {
        id: contactImporter
    }
    DekkoHeader {
        id: header
        title: qsTr("Addressbook")
        backAction: closeAction
        primaryAction: newContactAction
        secondaryActions: searchAction
        filterSections: [qsTr("All"), qsTr("Recent"), qsTr("Starred")]
        onSelectedIndexChanged: {

            if (header.state == "custom") {
                leaveSearchAction.trigger();
            }

            if (selectedIndex == 1) {
                recentListView.visible = true;
                contactList.visible = false;
                currentContactModel = recentContactModelFiltered
            } else {
                recentListView.visible = false;
                contactList.visible = true;
                currentContactModel = addressbookModelFiltered
            }

            if (selectedIndex == 0) {
                addressbookModelFiltered.filterRole = -1;
            } else if (selectedIndex == 2) {
                addressbookModelFiltered.filterRole = DekkoContactsModel.RoleStarred;
            }
            addressbookModelFiltered.invalidate();
        }

        customComponent:
            Component {
                Item {
                    anchors.fill: parent
                    HeaderButton {
                        id: cancelSearchButton
                        anchors {
                            top: parent.top
                            left: parent.left
                            leftMargin: units.gu(1)
                            bottom: parent.bottom
                        }
                        action: leaveSearchAction
                    }

                    TextField {
                         id: searchBox

                         anchors {
                             left: cancelSearchButton.right
                             margins: units.gu(1)
                             right: parent.right
                             verticalCenter: parent.verticalCenter
                         }
                         font.weight: Style.common.fontWeight
                         inputMethodHints: Qt.ImhNoPredictiveText
                         placeholderText: qsTr("Search contact")
                         primaryItem: Icon {
                              height: parent.height * 0.5
                              width: parent.height * 0.5
                              anchors.verticalCenter: parent.verticalCenter
                              name: "find"
                          }
                         onTextChanged: {
                             currentContactModel.setFilterFixedString(text.trim().toLowerCase());
                         }
                         Component.onCompleted: forceActiveFocus()
                    }
                }
            }
    }

    ListView {
        id: contactList
        clip: true
        anchors {
            top: header.bottom
            left: parent.left
            right: parent.right
            bottom: parent.bottom
        }
        model: addressbookModelFiltered
        delegate: AddressbookContactDelegate {
            displayStar: true
            onItemClicked: {
                internalStack.push(Qt.resolvedUrl("./ContactDetailPage.qml"), {
                                contact: {
                                       contactId: contactId,
                                       firstName: firstName,
                                       lastName: lastName,
                                       emails: emails,
                                       organization: organization,
                                       starred: starred
                                   }
                               }
                );
            }
            onRemoved: addressbookModel.removeContact(contactId);
            onIsStarredChanged: {
                addressbookModel.setStarred(contactId, isStarred)
            }
        }
        section {
            property: "tag"
            criteria: ViewSection.FirstCharacter
            delegate: SectionDelegate {
                anchors {
                    left: parent.left
                    right: parent.right
                }
                text: section != "" ? section : "#"
            }
        }
    }

    ListView {
        id: recentListView
        anchors {
            top: header.bottom
            left: parent.left
            right: parent.right
            bottom: parent.bottom
        }
        visible: false
        model: recentContactModelFiltered
        delegate: AddressbookContactDelegate {
            displayTime: true
            onItemClicked: {
                internalStack.push(Qt.resolvedUrl("./RecentContactDetailPage.qml"), {
                                contact: {
                                       contactId: contactId,
                                       firstName: firstName,
                                       emails: emails
                                   }
                               });
            }

            onRemoved: {
                recentContactModel.removeContact(contactId);
            }
        }
        section {
            property: "lastContactDateTag"
            criteria: ViewSection.FullString
            delegate: SectionDelegate {
                anchors {
                    left: parent.left
                    right: parent.right
                }
                text: section != "" ? section : "#"
            }
        }
    }
}
