import QtQuick 2.2
import Sailfish.Silica 1.0
import QtQuick.LocalStorage 2.0
import QtGraphicalEffects 1.0
import "../items"
import "../models"
import "../delegates"
import "../helpers/db.js" as Favorites
import "../helpers/jsFunctions.js" as JS

Page {

    id: page
    anchors.fill: parent
    anchors.bottomMargin: mediaPlayerPanel.visibleSize

    property int _appStart: Favorites.getSetting("appStart",0)
    property bool _loading: radioBrowser.loading
    property bool stationOk: radioPlayer.stationOk
    property bool online: radioBrowser.online
    property GetCountryStations getTrending1: GetCountryStations {id: getTrending1}
    property GetCountryStations getTrending2: GetCountryStations {id: getTrending2}
    property GetCountryStations getTrendingWorld: GetCountryStations {id: getTrendingWorld}
    property GetCountryStations getTags1: GetCountryStations {id: getTags1}
    property GetCountryStations getTags2: GetCountryStations {id: getTags2}
    property GetCountryStations getTags3: GetCountryStations {id: getTags3}
    property ListModel playedCountries: ListModel {id: playedCountries}
    property ListModel playedTags: ListModel {id: playedTags}
    property ListModel favorites: ListModel {id: favorites}

    onOnlineChanged: if (online) reloadDbData()
    onStationOkChanged: if (stationOk) reloadDbData()
    on_LoadingChanged: {
        if (!_loading) {
            appAutoPlay()
            //console.log(" *** AUTOPLAY")
        } //else console.log(" *** INTE AUTOPLAY")
    }

    Splash {
        id: splashItem
        visible: radioBrowser.loading ? true : false
    }

    SilicaFlickable {
        anchors.fill: parent
        contentHeight: mainColumn.height
        clip: mediaPlayerPanel.expanded
        visible: !splashItem.visible

        onVisibleChanged: if (visible) reloadDbData()

        PullDownMenu {
            MenuItem {
               text: qsTr("About")
               onClicked: pageStack.push("AboutPage.qml")
            }
            MenuItem {
               text: qsTr("Settings")
               onClicked: pageStack.push("SettingsPage.qml")
            }
            MenuItem {
               text: qsTr("Sleep timer")
               onClicked: {
                   pageStack.push("SleepTimerPage.qml")
               }
            }
        }

        Column {
            id: mainColumn
            width: parent.width
            spacing: Theme.paddingMedium

            Item {
                width: parent.width
                height: Theme.itemSizeHuge
                Label {
                    id: hlabel
                    font.pixelSize: Theme.fontSizeExtraLarge
                    text: JS.getGreeting()
                    color: Theme.highlightColor
                    anchors.verticalCenter: parent.verticalCenter
                    anchors.left: parent.left
                    anchors.leftMargin: Theme.paddingLarge
                }

                Image {
                    id: logo
                    anchors.verticalCenter: hlabel.verticalCenter
                    anchors.right: parent.right
                    anchors.rightMargin: Theme.paddingLarge
                    height: Theme.itemSizeMedium
                    width: height
                    smooth: true
                    source: "../images/community.png"
                }

                ColorOverlay {
                    anchors.fill: logo
                    source: logo
                    color: Theme.highlightColor
                }
            }

            BackgroundItem {
                width: parent.width
                height: Theme.itemSizeMedium

                ButtonRect {fill: false}

                Row {
                    anchors.left: parent.left
                    anchors.leftMargin: Theme.paddingLarge
                    anchors.verticalCenter: parent.verticalCenter
                    spacing: Theme.paddingMedium

                    Image {
                        anchors.verticalCenter: parent.verticalCenter
                        source: "image://theme/icon-m-search"
                    }

                    Label {
                        anchors.verticalCenter: parent.verticalCenter
                        text: qsTr("Search")
                        font.pixelSize: Theme.fontSizeLarge
                    }
                }

                Image {
                    anchors.right: parent.right
                    anchors.rightMargin: Theme.paddingLarge
                    anchors.verticalCenter: parent.verticalCenter
                    source: "image://theme/icon-m-right"
                }

                onClicked: pageStack.push("SearchStationsPage.qml",{searchby:"name"})}

                // Most played countries
            Column {
                //visible: playedCountries.count > 0
                width: parent.width

                Item {height: Theme.paddingLarge;width: parent.width}

                HeaderButton {
                    headerText: qsTr("Countries")
                    onClicked: pageStack.push("CountryListPage.qml")
                }

                Item {height: Theme.paddingMedium;width: parent.width}

                SilicaGridView {
                    clip: true
                    visible: playedCountries.count > 0
                    width: parent.width
                    height: playedCountries.count > 0 ? Theme.itemSizeExtraSmall * Math.round(playedCountries.count / 2) : 0
                    cellWidth: parent.width / 2
                    cellHeight: Theme.itemSizeExtraSmall
                    model: playedCountries
                    delegate: FavoriteCountryList {onClicked: pageStack.push("CountryStationsPage.qml",{searchby:"name",_countrycode: alpha_2})}
                }
            }

            // Most played favorites
            Item {height: Theme.paddingLarge;width: parent.width;visible: favorites.count > 0}

            HeaderButton {
                visible: favorites.count > 0
                headerText: qsTr("My Favorites")
                onClicked: pageStack.push("FavoritesPage.qml")
            }

            GridView {
                //clip: true
                id: favoriteView
                clip: true
                height: Theme.itemSizeHuge * 1.35
                width: page.width
                cellHeight: height
                cellWidth: cellHeight * 0.75
                flow: GridView.TopToBottom
                snapMode: SlideshowView.NoSnap
                layoutDirection: Qt.LeftToRight
                visible: favorites.count > 0

                model: favorites

                delegate: SmallStationsDelegate {
                    flagVisible: true

                    onClicked: {
                        if (model.url_resolved !== radioPlayer._url_resolved) {
                            radioPlayer._cc = model.countrycode// THIS IS THE FUNCTION DESTROYING AARCH64?!?
                            radioPlayer._favicon = model.favicon
                            radioPlayer._name = model.name
                            radioPlayer._tags = model.tags
                            radioPlayer._codec = model.codec
                            radioPlayer._bitrate = model.bitrate
                            radioPlayer._hls = model.hls
                            radioPlayer._url_resolved = model.url_resolved
                            radioPlayer._homepage = model.homepage
                            radioPlayer._stationuuid = model.stationuuid
                            radioPlayer.getStationFavorite(model.stationuuid)
                            radioPlayer.playlistIndex = index
                        } else radioPlayer.resumeStream()
                    }
                }
            }

            // Recently played
            Item {height: Theme.paddingLarge;width: parent.width;visible: radioPlayer.playHistory.count > 0}

            HeaderButton {
                visible: radioPlayer.playHistory.count > 0
                headerText: qsTr("Play history")
                onClicked: pageStack.push("HistoryPage.qml")
            }

            GridView {
                visible: radioPlayer.playHistory.count > 0
                clip: true
                height: playedTags.count > 0 ? Theme.itemSizeHuge * 1.35 : 0
                width: page.width
                cellHeight: height
                cellWidth: cellHeight * 0.75
                flow: GridView.TopToBottom
                snapMode: SlideshowView.NoSnap
                layoutDirection: Qt.LeftToRight

                model: radioPlayer.playHistory

                delegate: SmallStationsDelegate {
                    flagVisible: true
                    onClicked: {
                        if (model.url_resolved !== radioPlayer._url_resolved) {
                            radioPlayer._cc = model.countrycode// THIS IS THE FUNCTION DESTROYING AARCH64?!?
                            radioPlayer._favicon = model.favicon
                            radioPlayer._name = model.name
                            radioPlayer._tags = model.tags
                            radioPlayer._codec = model.codec
                            radioPlayer._bitrate = model.bitrate
                            radioPlayer._hls = model.hls
                            radioPlayer._url_resolved = model.url_resolved
                            radioPlayer._homepage = model.homepage
                            radioPlayer._stationuuid = model.stationuuid
                            radioPlayer.getStationFavorite(model.stationuuid)
                        } else radioPlayer.resumeStream()
                    }
                }
            }

            // Most played tags
            Item {height: Theme.paddingLarge;width: parent.width;visible: radioPlayer.playHistory.count > 0}

            HeaderButton {
                visible: radioPlayer.playHistory.count > 0
                headerText: qsTr("My most played Tags")
                onClicked: pageStack.push("TagListPage.qml",{})
            }

            GridView {
                visible: radioPlayer.playHistory.count > 0
                clip: true
                height: playedTags.count > 0 ? Theme.itemSizeHuge * 1.35 : 0
                width: page.width
                cellHeight: height
                cellWidth: cellHeight * 0.75
                flow: GridView.TopToBottom
                snapMode: SlideshowView.NoSnap
                layoutDirection: Qt.LeftToRight
                model: playedTags
                delegate: SmallTagsDelegate {
                    onClicked: pageStack.push("CountryStationsPage.qml",{filterby: "tag",searchby: "clicktrend",stext: tag,comboIndex: 1 })
                }
            }

            Item {height: Theme.paddingLarge;width: parent.width;visible: radioBrowser.getCountryName(_country) || playedCountries.count > 0 ? true : false}

            HeaderButton {
                visible: radioBrowser.getCountryName(_country) || playedCountries.count > 0 ? true : false
                headerText: playedCountries.count > 0 ? qsTr("Trending in")+ " " + radioBrowser.getCountryName(playedCountries.get(0).alpha_2) : qsTr("Trending in") + " " + radioBrowser.getCountryName(_country)
                onClicked: pageStack.push("CountryStationsPage.qml",{searchby:"clicktrend",_countrycode: playedCountries.count > 0 ? playedCountries.get(0).alpha_2 : _country})
            }

            GridView {
                clip: true
                height: Theme.itemSizeHuge * 1.35
                width: page.width
                cellHeight: height
                cellWidth: cellHeight * 0.75
                flow: GridView.TopToBottom
                snapMode: SlideshowView.NoSnap
                layoutDirection: Qt.LeftToRight
                visible: radioBrowser.getCountryName(_country) || playedCountries.count > 0 ? true : false

                model: getTrending1.searchModel

                delegate: SmallStationsDelegate {
                    flagVisible: false
                    onClicked: {
                        if (model.url_resolved !== radioPlayer._url_resolved) {
                            radioPlayer._cc = model.countrycode// THIS IS THE FUNCTION DESTROYING AARCH64?!?
                            radioPlayer._favicon = model.favicon
                            radioPlayer._name = model.name
                            radioPlayer._tags = model.tags
                            radioPlayer._codec = model.codec
                            radioPlayer._bitrate = model.bitrate
                            radioPlayer._hls = model.hls
                            radioPlayer._url_resolved = model.url_resolved
                            radioPlayer._homepage = model.homepage
                            radioPlayer._stationuuid = model.stationuuid
                            radioPlayer.getStationFavorite(model.stationuuid)
                        } else radioPlayer.resumeStream()
                    }
                }
            }

            Item {height: Theme.paddingLarge;width: parent.width;visible: playedCountries.count > 1}

            HeaderButton {
                visible: playedCountries.count > 1
                headerText: playedCountries.count > 1 ? qsTr("Trending in")+" " + radioBrowser.getCountryName(playedCountries.get(1).alpha_2) : qsTr("Trending in")+" " + radioBrowser.getCountryName(_country)
                onClicked: pageStack.push("CountryStationsPage.qml",{searchby:"clicktrend",_countrycode: playedCountries.get(1).alpha_2})
            }

            GridView {
                clip: true
                height: Theme.itemSizeHuge * 1.35
                width: page.width
                cellHeight: height
                cellWidth: cellHeight * 0.75
                flow: GridView.TopToBottom
                snapMode: SlideshowView.NoSnap
                layoutDirection: Qt.LeftToRight
                visible: playedCountries.count > 1

                model: getTrending2.searchModel

                delegate: SmallStationsDelegate {
                    flagVisible: false
                    onClicked: {
                        if (model.url_resolved !== radioPlayer._url_resolved) {
                            radioPlayer._cc = model.countrycode// THIS IS THE FUNCTION DESTROYING AARCH64?!?
                            radioPlayer._favicon = model.favicon
                            radioPlayer._name = model.name
                            radioPlayer._tags = model.tags
                            radioPlayer._codec = model.codec//getCodec(model.codec)
                            radioPlayer._bitrate = model.bitrate //getBitrate(model.bitrate)
                            radioPlayer._hls = model.hls
                            radioPlayer._url_resolved = model.url_resolved
                            radioPlayer._homepage = model.homepage
                            radioPlayer._stationuuid = model.stationuuid
                            radioPlayer.getStationFavorite(model.stationuuid)
                        } else radioPlayer.resumeStream()
                    }
                }
            }

            Item {height: Theme.paddingLarge;width: parent.width}

            HeaderButton {
                headerText: qsTr("Trending in the world")
                onClicked: pageStack.push("CountryStationsPage.qml",{searchby:"clicktrend",_countrycode: ""})
            }

            GridView {
                clip: true
                height: Theme.itemSizeHuge * 1.35
                width: page.width
                cellHeight: height
                cellWidth: cellHeight * 0.75
                flow: GridView.TopToBottom
                snapMode: SlideshowView.NoSnap
                layoutDirection: Qt.LeftToRight
                model: getTrendingWorld.searchModel
                delegate: SmallStationsDelegate {
                    flagVisible: true
                    onClicked: {
                        if (model.url_resolved !== radioPlayer._url_resolved) {
                            radioPlayer._cc = model.countrycode// THIS IS THE FUNCTION DESTROYING AARCH64?!?
                            radioPlayer._favicon = model.favicon
                            radioPlayer._name = model.name
                            radioPlayer._tags = model.tags
                            radioPlayer._codec = model.codec//getCodec(model.codec)
                            radioPlayer._bitrate = model.bitrate //getBitrate(model.bitrate)
                            radioPlayer._hls = model.hls
                            radioPlayer._url_resolved = model.url_resolved
                            radioPlayer._homepage = model.homepage
                            radioPlayer._stationuuid = model.stationuuid
                            radioPlayer.getStationFavorite(model.stationuuid)
                        } else radioPlayer.resumeStream()
                    }
                }
            }
        }
    }

    function appAutoPlay() {
        switch (_appStart) {
            case 0:
                break;
            case 1:
                radioPlayer.loadRecentPlay()
                radioPlayer.playStream()
                break;
            case 2:
                radioPlayer.loadRandomPlay()
                radioPlayer.playStream()
                break;
            default:
                break;
        }
    }

    function reloadDbData() {
        Favorites.getTagsRecentClicked(playedTags,15)
        Favorites.getFavorites(favorites,"myclickcount",15)
        Favorites.getCountryRecentClicked(playedCountries,4)
        getTrending1.countrycode = playedCountries.count > 0 ? playedCountries.get(0).alpha_2 : _country
        getTrending1.order = "clicktrend"
        getTrending1.offset = 0
        getTrending1.limit = 15
        if (getTrending1.searchModel.count !== 0) getTrending1.clear = true; else getTrending1.getStations()

        if (playedCountries.count > 1) {
            getTrending2.countrycode = playedCountries.get(1).alpha_2
            getTrending2.order = "clicktrend"
            getTrending2.offset = 0
            getTrending2.limit = 15
            if (getTrending2.searchModel.count !== 0) getTrending2.clear = true; else getTrending2.getStations()
        }

        getTrendingWorld.countrycode = ""
        getTrendingWorld.order = "clicktrend"
        getTrendingWorld.offset = 0
        getTrendingWorld.limit = 15
        if (getTrendingWorld.searchModel.count !== 0) getTrendingWorld.clear=true; else getTrendingWorld.getStations()
    }

    Component.onCompleted: {
        Favorites.init()
        radioBrowser.getList()
        reloadDbData()
    }
}

