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 _cc: ""
    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: ""  // For future implementation?!
   // property string _trend: ""
    property bool _favorite: false
    //--------------------------------
    property bool playerPageOpen: 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: 0
    property int maxTagClicks: 0
    property int playlistCount: playlist.count -1
    property int playlistIndex: Favorites.getSetting("playlistIndex",-1)
    property ListModel playHistory: ListModel {id: playHistory}
    property ListModel playlist: ListModel {id: playlist}
    property QDtimer timer: QDtimer {
        id: qdTimer
        interval: 200; running: false; repeat: false
    }

    autoPlay: false
    autoLoad: true

    onPlaying: if (!playerPageOpen) pageStack.push("../pages/RadioPlayerPage.qml")

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

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

    on_StationuuidChanged: {
        radioCountryName = radioBrowser.getCountryName(_cc)
        stop()
        source = ""
        radioVideo = false
        radioAudio = false
        isPaused = false
        isPlaying = false
        stationOk = 0
        getStationUrl(_stationuuid);
    }

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

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

    onStatusChanged: {
        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 status1 () { // NoMedia
        radioStatus = status
        radioStatusString = "No Media"
    }

    function status2 () { // Loading
        radioStatus = status
        radioStatusString = "Loading"
    }

    function status3 () { // Loaded
        radioStatus = status
        radioStatusString = "Loaded"
    }

    function status4 () { // Buffering
        radioStatus = status
        radioStatusString = "Buffering"
    }

    function status5 () { // Stalled
        radioStatus = status
        radioStatusString = "Stalled"
        notification.category = "Status"
        notification.summary = _name
        notification.body = "Stalled"
        notification.publish()
        radioPlayer.stopStream()
    }

    function status6 () { // Buffered
        radioStatus = status
        radioStatusString = "Buffered"
    }

    function status7 () { // EndOfMedia
        radioStatus = status
        radioStatusString = "End Of Media"
        notification.category = "Status"
        notification.summary = _name
        notification.body = "End of media"
        notification.publish()
        radioPlayer.resumeStream()
    }

    function status8 () { // InvalidMedia
        radioStatus = status
        radioStatusString = "Invalid Media"
        notification.category = "Status"
        notification.summary = _name
        notification.body = "Invalid media"
        notification.publish()
        radioPlayer.stopStream()
    }

    function status9 () { // UnknownStatus
        radioStatus = status
        radioStatusString = "Unknown Status"
    }

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

    function playNext() {
        if (playlistIndex < playlistCount) playlistIndex = playlistIndex + 1
        loadPlaylistSelected()
    }

    function playPrev() {
        if (playlistIndex <= playlistCount) playlistIndex = playlistIndex - 1
        loadPlaylistSelected()
    }

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

    function pauseStream() {
        isPlaying = false
        source = ""
        stop()
    }

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

    function playStream() {
        source = _url_resolved
        play()
        isPlaying = true
        isPaused = false
        qdTimer.start()
        if (_favorite) Favorites.setSetting("playlistIndex",playlistIndex)
        //appStartPlay = false
    }

    function tryagain() {
        tryTimer.running = true
    }



    function setStationClick() {
        Favorites.setStationClicked(JsFunctions.getTimeStamp(),_stationuuid,_name,_cc,_homepage,_url_resolved,_favicon,_tags,_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,"myclickcount",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
            _cc = 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
            _cc = 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
            ///if (_favorite) playlistCount = Favorites.getSetting("playlistIndex",-1)
            //playlistIndex = allradioSettings.value("currentFavorite",-1)
        //    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
            _cc = 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
        }
    }
    // Register as radio station click on community radio and get station info from Community Radio and save it to Db. Initiate playback.
    function getStationUrl(id) {
        var req = new XMLHttpRequest();
        req.onreadystatechange = function () {
            if (req.readyState === 4 && req.status < 300) {
                var temp = req.responseText
                var ok = temp.indexOf('status ok="true"') !== -1
                if (ok) {
                    stationOk = 1
                } else {
                    stationOk = 0
                }
            }
        };
        req.open("post", radioBrowser.serverUrl + "/xml/url/" +id);
        req.setRequestHeader('User-Agent',radioBrowser._useragent);
        req.send();
    }

    Component.onCompleted: {reloadDbData();_favorite ? loadPlaylistSelected() : loadRecentPlay()}
}

