import QtQuick 2.0
import QtMultimedia 5.6
import QtQuick.LocalStorage 2.0

import "../helpers/jsFunctions.js" as JsFunctions
import "../helpers/db.js" as Favorites
import "../items"

MediaPlayer {
    // Media info from clicking play
    property string _stationuuid: ""
    property string _name: ""
    property string _favicon: ""
    property string _countrycode: ""
    property string _tags: ""
    property string _codec: ""
    property string _bitrate: ""
    property string _hls: ""
    property string _url_resolved: ""
    property string _homepage: ""
   // property string _votes: ""
   // property string _plays: ""
   // property string _trend: ""
    property bool _favorite: false
    //--------------------------------
   // property bool videoP: false

    property bool playerPageOpen: false
//    property bool jupiiOn: false
    property string radioId: ""
    property string metaInfo: metaData.title ? metaData.title : ""
    property string radioArtist: ""
    property string radioSong: ""
    property bool radioVideo: false
    property bool radioAudio: false
    property string radioCountryName
    property string radioHLS: JsFunctions.getHLS(_hls)
    property string radioCodec: JsFunctions.getCodec(_codec)
    property string radioBitrate: JsFunctions.getBitrate(_bitrate)
    property real radioBufferProgress: bufferProgress
    property int radioStatus
    property string radioStatusString
    property bool isPlaying: false
    property bool isPaused: false
    property int stationOk: 3
    property int maxTagClicks: 0
    property int playlistCount: playlist.count - 1
    property int playlistIndex: allradioSettings.value("currentFavorite",-1)
    property QDtimer timer: QDtimer {id: qdTimer}
    //property string videoOut: ""
//    property ListModel mostPlayedFavorites: ListModel {id: mostPlayedFavorites}
   //videoOutput: videoOut
//    property variant magnitudeArray: null
//    property int millisecondsPerBar: 68

    property ListModel playHistory: ListModel {id: playHistory}
    property ListModel playlist: ListModel {id: playlist}


    autoPlay: false
    autoLoad: true


    //on_FavoriteChanged: {setStationFavorite(_stationuuid,_name,_countrycode,_homepage,_url_resolved,_favicon,_tags,_codec,_bitrate,_hls,_favorite);Favorites.getMostPlayedFavorites(mostPlayedFavorites,15)}
    onPlaying: if (!playerPageOpen) pageStack.push("../pages/RadioPlayerPage.qml")

       // onPlaylistIndexChanged: loadPlaylistSelected()

    onMetaInfoChanged: {
     //   console.log(" ******* METAINFO: "+metaInfo)
        if (metaInfo.search(" - ") > -1) {
            var res = metaInfo.split(" - ")
            radioArtist = res[0]
            radioSong = res[1]
        } else {
            radioArtist = metaInfo
            radioSong = ""
        }
    }

    onRadioAudioChanged: {
     //   if (hasVideo) console.log(" *** VIDEO"); else console.log(" *** AUDIO")
    }

    onStationOkChanged: {
     //   console.log("StationOK?: "+stationOk)
        if (stationOk === 1) {
            setStationClick()
            getStationFavorite(_stationuuid)
            playStream()
            stationOk === 0
            reloadDbData()
            if (_favorite) allradioSettings.setValue("currentFavorite",playlistIndex)
        }
    }

    on_StationuuidChanged: { //if (_stationuuid !== "") {getStationUrl(_stationuuid);radioPlayUrl = _url_resolved} else radioPlayUrl = ""
        radioCountryName = radioBrowser.getCountryName(_countrycode)
        stop()
        source = ""
        //metaInfo = ""
        radioVideo = false
        radioAudio = false
        isPaused = false
        isPlaying = false
        stationOk = 3
        getStationUrl(_stationuuid);
    }

    //onIsPausedChanged: if (_paused) {
                          //radioPlaying = false
                          ///radioPaused = true
                       //   radioSource = ""
                    //      metaInfo = ""
                    //      if(radioVideo) {
                      //       videoPlayer.visible = false
                       //       radioSource = ""
                      //    }
            //          }

    onHasVideoChanged: if (hasVideo) radioVideo = true
    onHasAudioChanged: if (hasAudio) radioAudio = true

    function stopStream() { // stop and clear stream
        source = ""
        isPaused = false
        isPlaying = false
        radioArtist = ""
        radioSong = ""
        radioVideo = false
        radioAudio = false
        stationOk = 3
        _stationuuid = ""
        _name = ""
        _favicon = ""
        _countrycode = ""
        _tags = ""
        _codec = ""
        _bitrate = ""
        _hls = ""
        _homepage = ""
        stop()
      //  metaInfo = ""
    }


    function videoPause() {
        source = ""
        stop()

    }


    function pauseStream() { // stop stream without clear


        isPaused = true
        isPlaying = false
        source = ""
        stop()
      //  metaInfo = ""
    }

    function resumeStream() {
        isPlaying = true
        isPaused = false
        playStream()

    }



    function playStream() { // resume paused stream
        //radioSource = ""


        source = _url_resolved
        play()
        isPlaying = true
        isPaused = false
        qdTimer.start()
       // play()
    }

    onError: {
        notification.category = "Error"
        notification.summary = _name
        //notification.subText = _name
        notification.body = errorString
        notification.publish()
        radioPlayer.stopStream()

    }

   /* onRadioStatusChanged: {
        notification.body = radioStatusString
        notification.publish()
    }*/




    onStatusChanged: {
        //console.log(" ___ STATUS: "+status)
        switch (status) {
            case 1: status1();break; // NoMedia
            case 2: status2();break; // Loading
            case 3: status3();break; // Loaded
            case 4: status4();break; // Buffering
            case 5: status5();break; // Stalled
            case 6: status6();break; // Buffered
            case 7: status7();break; // EndOfMedia
            case 8: status8();break; // InvalidMedia
            case 9: status9();break; // UnknownStatus
        }
    }
    function tryagain() {
        tryTimer.running = true
    }
    function status1 () { // NoMedia
        radioStatus = status
        radioStatusString = "No Media"
        //console.log("Status: No Media")
    }
    function status2 () { // Loading
        radioStatus = status
        radioStatusString = "Loading"
        //console.log("Status: Loading")
    }
    function status3 () { // Loaded
        radioStatus = status
        radioStatusString = "Loaded"
        //console.log("Status: Loaded")
    }
    function status4 () { // Buffering
        radioStatus = status
        radioStatusString = "Buffering"
        //console.log("Status: Buffering")
    }
    function status5 () { // Stalled
        radioStatus = status
        radioStatusString = "Stalled"
        notification.category = "Status"
        notification.summary = _name
        //notification.subText = _name
        notification.body = "Stalled"
        notification.publish()
        //console.log("Status: Stalled")
        radioPlayer.stopStream()
    }
    function status6 () { // Buffered
        radioStatus = status
        radioStatusString = "Buffered"
        //console.log("Status: Buffered")
    }
    function status7 () { // EndOfMedia
    /*    if (errorCount<4) {
        //errorCount = errorCount + 1
        tryTimer.start()
        }else{ */
        radioStatus = status
        radioStatusString = "End Of Media"
        notification.category = "Status"
        notification.summary = _name
        //notification.subText = _name
        notification.body = "End of media"
        notification.publish()
        //console.log("Status: End Of Media")
        radioPlayer.stopStream()
      //  }
    }
    function status8 () { // InvalidMedia
        radioStatus = status
        radioStatusString = "Invalid Media"
        notification.category = "Status"
        notification.summary = _name
        //notification.subText = _name
        notification.body = "Invalid media"
        notification.publish()
        //console.log("Status: Invalid Media")
        radioPlayer.stopStream()
    }
    function status9 () { // UnknownStatus
        radioStatus = status
        radioStatusString = "Unknown Status"
        //console.log("Status: Unknown Status")
    }

    function getStationUrl(id) { // Register as radio station click on community radio and get station info from Community Radio and save it to Db. Initiate playback.
        var req = new XMLHttpRequest();
        req.open("post", radioBrowser.serverUrl + "/xml/url/" +id, true);
       // console.log(radioBrowser.serverUrl)
        req.responseType = "document";
        req.setRequestHeader('User-Agent',radioBrowser._useragent);
        req.onreadystatechange = function () {
            if (req.readyState === 4 && req.status === 200) {
                var temp = req.responseText
                var ok = temp.indexOf('status ok="true"') !== -1
             //   console.log("OK: "+ok)
                if (ok) {
                    stationOk = 1
                } else {
                    stationOk = 0
                }
            } //else if (req.readyState === 4) {stationOk = 2}
        };
        req.send();
    }
    function setStationClick() {
        //getStationFavorite(_stationuuid)
        Favorites.setStationClicked(JsFunctions.getTimeStamp(),_stationuuid,_name,_countrycode,_homepage,_url_resolved,_favicon,_tags,_codec,_bitrate,_hls,_favorite)

        //  property bool favo: isFavorite(stationuuid) ? true : false

        //getIfFavorite(_stationuuid)
        //getIfFavorite(_stationuuid)
    }                        //   myclicktimestamp,id,name,countrycode,homepage,radiourlresolved,favicon,tagslist,codec,bitrate,hls,favorite
    function setStationFavorite(stationuuid,name,countrycode,homepage,url_resolved,favicon,tags,codec,bitrate,hls,favorite) {
        Favorites.setStationFavorite(stationuuid,name,countrycode,homepage,url_resolved,favicon,tags,codec,bitrate,hls,favorite)
    }
    function getStationFavorite(id){
        _favorite = Favorites.getStationFavorite(id)
    }

    function reloadDbData() {
        Favorites.getStationRecentClicked(playHistory,15)
        Favorites.getFavorites(playlist,"name",10000)
        //Favorites.getStationMostClickedFav(radioPlayermostPlayed,settings._nrOfFavoritePreview)
        //Favorites.getCountryRecentClicked(playedCountries,2)
        //Favorites.getTagsRecentClicked(playedTags,10)
        //Favorites.getMostPlayedFavorites(mostPlayedFavorites,15)
    }
    function loadPlaylistSelected(){
        if (playlist.get(playlistIndex).url_resolved) {
            _favicon = playlist.get(playlistIndex).favicon
            _name = playlist.get(playlistIndex).name
            _countrycode = playlist.get(playlistIndex).countrycode
            _tags = playlist.get(playlistIndex).tags
            _codec = playlist.get(playlistIndex).codec//getCodec(model.codec)
            _bitrate = playlist.get(playlistIndex).bitrate //getBitrate(model.bitrate)
            _hls = playlist.get(playlistIndex).hls
            _url_resolved = playlist.get(playlistIndex).url_resolved
            _homepage = playlist.get(playlistIndex).homepage
            _stationuuid = playlist.get(playlistIndex).stationuuid
            _favorite = playlist.get(playlistIndex).favorite
            isPlaying = true
            isPaused = false
            playStream()
        //    pageStack.push("RadioPlayerPage.qml")
        }
    }
    function loadRecentPlay(){
        if (playHistory.get(0).url_resolved) {
            _favicon = playHistory.get(0).favicon
            _name = playHistory.get(0).name
            _countrycode = playHistory.get(0).countrycode
            _tags = playHistory.get(0).tags
            _codec = playHistory.get(0).codec//getCodec(model.codec)
            _bitrate = playHistory.get(0).bitrate //getBitrate(model.bitrate)
            _hls = playHistory.get(0).hls
            _url_resolved = playHistory.get(0).url_resolved
            _homepage = playHistory.get(0).homepage
            _stationuuid = playHistory.get(0).stationuuid
            _favorite = playHistory.get(0).favorite
            isPlaying = false
            isPaused = true
        //    pageStack.push("RadioPlayerPage.qml")
        }
    }
    function loadRandomPlay(){
        var rnd = Math.floor(Math.random() * playlist.count)
        if (playlist.get(rnd).url_resolved) {
            _favicon = playlist.get(rnd).favicon
            _name = playlist.get(rnd).name
            _countrycode = playlist.get(rnd).countrycode
            _tags = playlist.get(rnd).tags
            _codec = playlist.get(rnd).codec//getCodec(model.codec)
            _bitrate = playlist.get(rnd).bitrate //getBitrate(model.bitrate)
            _hls = playlist.get(rnd).hls
            _url_resolved = playlist.get(rnd).url_resolved
            _homepage = playlist.get(rnd).homepage
            _stationuuid = playlist.get(rnd).stationuuid
            _favorite = playlist.get(rnd).favorite
            isPlaying = false
            isPaused = true
        //    pageStack.push("RadioPlayerPage.qml")
        }
    }

    function updateMprisMetadata(){
            mprisPlayer.song = metaInfo ? metaInfo : ""
            mprisPlayer.artist = radioStation === "" ? "AllRadio" : radioStation
            updatePlaybackStatus()
    }

    function updatePlaybackStatus (){
        switch (playMusic.playbackState) {
            case Audio.PlayingState:
                mprisPlayer.playbackStatus = Mpris.Playing
                break;

            case Audio.PausedState:
                mprisPlayer.setCanPause(false)
                mprisPlayer.playbackStatus = Mpris.Paused
                break;
            case Audio.StoppedState:
                mprisPlayer.playbackStatus = Mpris.Paused
                break;
            default:
                mprisPlayer.playbackStatus = Mpris.Paused
        }
    }




    Component.onCompleted: {reloadDbData();loadRecentPlay()}
}

