$(function () {
    const webSocket = window.socket;
    var lastFollow    = '-',
        lastSub       = '-',
        lastDonator   = '-',
        countFollow   = 0,
        countSub      = 0,
        timer         = '-';

    const getQueryMap = () => {
        let queryString = window.location.search,
            queryParts = queryString.substring(1).split('&'),
            queryMap = new Map();

        for (let part of queryParts) {
            let key = part.substring(0, part.indexOf('=')),
                value = part.substring(part.indexOf('=') + 1, part.length);
            if (key.length > 0 && value.length > 0) queryMap.set(key, value);
        }
        return queryMap;
    }
    const queryMap = getQueryMap();
    Map.prototype.getOrElse = (option, def) => queryMap.has(option) ?  queryMap.get(option): def;

    const refreshUI = () => {
        if(queryMap.getOrElse('single',false)){ 
            $('#all').show(); $('#timer').hide(); $('#goal').hide();
            $('#follow').parent().closest('div').hide(); $('#subscribe').parent().closest('div').hide(); $('#donate').parent().closest('div').hide();
            if(queryMap.getOrElse('follow',false)) $('#follow').parent().closest('div').show(); 
            if(queryMap.getOrElse('subscribe',false)) $('#subscribe').parent().closest('div').show(); 
            if(queryMap.getOrElse('donate',false)) $('#donate').parent().closest('div').show(); 
        }else if(queryMap.getOrElse('goal',false)){ 
            $('#all').hide(); $('#timer').hide(); $('#goal').show();
            $('#cfollow').parent().closest('div').hide(); $('#csubscribe').parent().closest('div').hide(); 
            if(queryMap.getOrElse('follow',false)) $('#cfollow').parent().closest('div').show(); 
            if(queryMap.getOrElse('subscribe',false)) $('#csubscribe').parent().closest('div').show(); 
        }

        $('#follow').text(lastFollow);
        $('#subscribe').text(lastSub);
        $('#donate').text(lastDonator);
        $('#cfollow').parent().closest('div').progressbar({ value : countFollow/parseInt(queryMap.getOrElse('follow',9999))*100 });
        $('#csubscribe').parent().closest('div').progressbar({ value : countSub/parseInt(queryMap.getOrElse('subscribe',9999))*100});
        $('#cfollow').text(`${countFollow} / ${queryMap.getOrElse('follow',9999)}`);
        $('#csubscribe').text(`${countSub} / ${queryMap.getOrElse('subscribe',9999)}`);
    }

    const handleSocketMessage = (e)=>{
        try {
            let rawMessage = e.data,
                message = JSON.parse(rawMessage);

            if(!message.hasOwnProperty('eventFamily') || message.eventFamily != 'overlay' || 
                !message.hasOwnProperty('eventType') || !message.hasOwnProperty('data'))
                return;

            console.log(message.eventType, message.data)
            if(message.eventType == 'follow') {
                lastFollow = message.data || lastFollow;
                countFollow++;
            } else if(message.eventType == 'subscribe') {
                lastSub = message.data || lastSub;
                countSub++;
            } else if(message.eventType == 'donation') {
                lastDonator = message.data || lastDonator;
            } else if(message.eventType == 'timer') {
                console.log("New timer !! ", message.data)
            }
            refreshUI();
        } catch (ex) {
            console.log(ex)
        }
    };


    jQuery(async ()=>{
        refreshUI();
        try{
            socket.addFamilyHandler("overlay", handleSocketMessage);
            if(socket){
                while(socket.getReadyState() === 0){
                    await new Promise(r => setTimeout(r, 500));
                }
                socket.getDBValue("get_current_stream_info_lastFollow", 'streamInfo', 'lastFollow', (response)=>{
                    if(response.streamInfo) lastFollow = response.streamInfo || lastFollow;
                    refreshUI();
                })
                socket.getDBValue("get_current_stream_info_lastSub", 'streamInfo', 'lastSub', (response)=>{
                    if(response.streamInfo) lastSub = response.streamInfo || lastSub;
                    refreshUI();
                })
                socket.getDBValue("get_current_stream_info_lastDonator", 'streamInfo', 'lastDonator', (response)=>{
                    if(response.streamInfo) lastDonator = response.streamInfo || lastDonator;
                    refreshUI();
                })
                socket.getDBValue('get_current_stream_info_counts', 'panelData', 'stream', (e)=>{
                    let data = JSON.parse(e.panelData);
                    countFollow = data.followers || countFollow;
                    countSub = 0;
                    refreshUI();
                })
            }
        }catch(e) {console.log(e)}
    })

});