import QtQuick 2.0
import Sailfish.Silica 1.0
import "../models"
import "../delegates"
//import "../radio-browser"

Page {
    property string sortedby: ""
    property string filterby
    property alias searchby: getCountryStations.order
    property string searchtext: ""
    property string _countrycode: ""
    property int stationCount: 0
    property alias name: getCountryStations.name
    property alias tag: getCountryStations.tag
    property GetCountryStations getCountryStations: GetCountryStations {id: getCountryStations}
    property bool sfocus

    onStatusChanged: if (status !== PageStatus.Active) sfocus=false

    onSearchbyChanged: {
    //    console.log("SEARCHBY: "+searchby)
        switch (searchby){
            case "name": sortedby = qsTr("By Name");break;
            case "votes": sortedby = qsTr("Most likes");break;
            case "clicktrend": sortedby = qsTr("Trending right now");break;
            case "clickcount": sortedby = qsTr("Most played");
        }
    }

    BusyIndicator {
        id: busy
        visible: running
        anchors.centerIn: parent
        size: BusyIndicatorSize.Large
        running: !getCountryStations.finished && getCountryStations.offset > 0
    }

    SilicaListView {
        id: view
        enabled: !busy.visible
        opacity: enabled ? 1 : 0.5
        anchors.fill: parent

        clip: mediaPlayerPanel.expanded
        anchors.bottomMargin: sfocus ? 0 : mediaPlayerPanel.visibleSize

        ViewPlaceholder {
            anchors.centerIn: parent
            enabled: view.count == 0
            text: getCountryStations.finished && view.count === 0 ? qsTr("Search") : qsTr("Please wait")
            hintText: getCountryStations.finished && view.count === 0 ? qsTr("radio stations") : qsTr("getting radio stations")
        }

        VerticalScrollDecorator {}

        onAtYEndChanged: {
            if (atYEnd && view.count >= getCountryStations.limit) {
            //    console.log("AT BOTTOM: "+view.count)
                if (getCountryStations.offset + getCountryStations.limit < stationCount) {
                    getCountryStations.offset = getCountryStations.offset + getCountryStations.limit + 1
                    getCountryStations.getStations()
                }
            }
        }

        header: Column {
            width: parent.width

            PageHeader {
               id: pheader


               Column {
                   id: headerCol
                   anchors.top: parent.top
                   anchors.topMargin: Theme.paddingLarge
                   anchors.right: parent.right
                   anchors.left: parent.left
                   anchors.rightMargin: Theme.paddingLarge//headerLogo.width + (Theme.paddingLarge * 2)
                   anchors.leftMargin: Theme.paddingLarge
                   Row {
                       anchors.right: parent.right
                       spacing: Theme.paddingMedium
                       Image {
                           id: headerLogo
                           anchors.bottom: ccode.bottom
                           height: ccode.height * 0.8
                           fillMode: Image.PreserveAspectFit
                           smooth: true
                           source: _countrycode === "" ? "../images/bycountry_t.png" : "../flags/"+_countrycode.toLowerCase()+".png"
                       }
                       Label {
                           id: ccode
                           font.pixelSize: Theme.fontSizeLarge
                           color: Theme.highlightColor
                           wrapMode: Text.WordWrap
                           elide: Text.ElideLeft
                           text: getCountryStations.country //+ " ["+stationCount+"]"
                       }
                   }
                   Label {
                       font.pixelSize: Theme.fontSizeSmall
                       color: Theme.secondaryHighlightColor
                       width: parent.width
                       horizontalAlignment: Text.AlignRight
                       text: sortedby//view.count + " channels"
                   }
               }
            }

            Row {
                id: row
                width: parent.width
                SearchField {
                    id: sfield
                    placeholderText: qsTr("Search")
                    inputMethodHints: Qt.ImhNoAutoUppercase //| Qt.ImhNoPredictiveText
                    EnterKey.iconSource: "image://theme/icon-m-enter-close"
                    EnterKey.onClicked: focus = false
                    focus: sfocus

                    onFocusChanged: {
                        sfocus = focus
                        //radioPlayer.isPlaying || radioPlayer.isPaused && !focus ? mediaPlayerPanel.open = false : mediaPlayerPanel.open = true
                    }

                    onTextChanged: {
                        if (searchtext !== text) {
                     //   console.log(" *** TEXT CHANGED: "+searchCombo.currentIndex+" --- TEXT: "+text)
                        if (text.length > 0) {
                            searchtext = text
                            switch(searchCombo.currentIndex) {
                                case 0: filterby="name";getCountryStations.offset=0;getCountryStations.name=text;getCountryStations.tag="";break
                                case 1: filterby="tag";getCountryStations.offset=0;getCountryStations.tag=text;getCountryStations.name=""
                            }
                        } else {
                            getCountryStations.name=""
                            getCountryStations.tag=""
                        }
                        getCountryStations.offset=0;
                        getCountryStations.clear = true
                        if (text !== "") getCountryStations.getStations()
                    }
                    }
                    onClicked: {view.currentIndex = -1}

                }
            }

            ComboBox {
                id: searchCombo
                label: qsTr("Search by:")
                currentIndex: 0
                menu: ContextMenu {
                    MenuItem { text: qsTr("Name") }
                    MenuItem { text: qsTr("Tag") }
                }
                onValueChanged: {
                    switch(currentIndex) {
                        case 0: filterby="name";getCountryStations.offset=0;getCountryStations.name=sfield.text;getCountryStations.tag="";break
                        case 1: filterby="tag";getCountryStations.offset=0;getCountryStations.tag=sfield.text;getCountryStations.name=""
                    }
                    if (searchtext.length !== 0) {
                        getCountryStations.offset=0;
                        getCountryStations.clear = true
                        getCountryStations.getStations()
                    }
                }
            }

        }

        PullDownMenu {
            MenuItem {
                text: qsTr("Name")
                onClicked: {getCountryStations.order = "name";if (view.count > 0) {getCountryStations.clear=true;getCountryStations.getStations()}}//;xmlModel.running = true}
            }

            MenuItem {
                text: qsTr("Most likes")
                onClicked: {getCountryStations.order = "votes";if (view.count > 0) {getCountryStations.clear=true;getCountryStations.getStations()}}//;xmlModel.running = true}
            }
            MenuItem {
                text: qsTr("Most played")
                onClicked: {getCountryStations.order = "clickcount";if (view.count > 0) {getCountryStations.clear=true;getCountryStations.getStations()}}//xmlModel.running = true}
            }
            MenuItem {
                text: qsTr("Trending right now")
                onClicked: {getCountryStations.order = "clicktrend";if (view.count > 0) {getCountryStations.clear=true;getCountryStations.getStations()}}//xmlModel.running = true}
            }
        }

        model: getCountryStations.stationsModel
        delegate: StationsDelegate{
            onClicked: {
                if (model.url_resolved !== radioPlayer._url_resolved) {
                    radioPlayer._favicon = model.favicon
                    radioPlayer._name = model.name
                    radioPlayer._cc = model.countrycode
                    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._favorite = model.favorite ? true : false
                    radioPlayer.getStationFavorite(model.stationuuid)
                  //  pageStack.push("RadioPlayerPage.qml")
                } else radioPlayer.resumeStream()
            }
        }
    }
    Component.onCompleted: {
        //MediaPlayerPanel.open = false
        getCountryStations.countrycode=""
        getCountryStations.order=searchby
        //getCountryStations.getStations()
    }
   // Component.onDestruction: if (radioPlayer.isPlaying || radioPlayer.isPaused) mediaPlayerPanel.open ? mediaPlayerPanel.open = false : mediaPlayerPanel.open = true
}