import QtQuick 2.0
import Sailfish.Silica 1.0
import io.thp.pyotherside 1.3

Page {
    property alias mainList: mainList
    SilicaFlickable {
        id: mainList
        anchors.fill: parent

        PullDownMenu {
            MenuItem {
                text: "About"
                onClicked: pageStack.push(Qt.resolvedUrl("About.qml"))
            }
            MenuItem {
                text: "Refresh"
                onClicked: mainList.reload()
            }
        }

        PageHeader {
            id: header
            width: parent.width
            title: "Select the webapp to unify"
        }

        SilicaGridView {

            anchors.top: header.bottom
            width: parent.width
            height: parent.height
            cellWidth: width / 4
            cellHeight: cellWidth

            model: ListModel {
                id: appsList
            }

            delegate: GridItem {
                menu: Component {
                    ContextMenu {
                        MenuItem {
                            text: attrs.Name
                        }
                        MenuItem {
                            text: "Restore the old icon"
                            onClicked: {
                                py.addImportPath(Qt.resolvedUrl("../src"))
                                py.importModule("main", function(){
                                    py.call("main.restore_icon", [attrs], function(success) {
                                        if(success) mainList.reload();
                                    })
                                })
                            }
                        }
                    }
                }

                Image {
                    anchors.centerIn: parent
                    source: attrs.Icon
                    width: parent.width
                    height: width
                }

                onClicked: {
                    pageStack.push(Qt.resolvedUrl("Icon.qml"), {attrs: attrs});
                }
            }
        }

        function reload(){
            appsList.clear()
            py.addImportPath(Qt.resolvedUrl("../src"))
            py.importModule("main", function(){
                py.call("main.get_web_icons", [], function(apps){
                    for(var i=0; i < apps.length; i++){
                        appsList.append({attrs: apps[i]})
                    }
                })
            })
        }

        Python {
            id: py

            Component.onCompleted: {
                mainList.reload()
            }
        }
    }

}
