$(function () {
    const webSocket = window.socket;
    var guesses    = {},
        status       = '-',
        hidden   = false;

    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;
    }
    Map.prototype.getOrElse = (option, def) => queryMap.has(option) ?  queryMap.get(option): def;
    const queryMap = getQueryMap();



    $('#showhide').on('click',()=>{
        if(hidden){
            $('.containing').show();
            hidden = false;
        }else{
            $('.containing').hide();
            hidden = true;
        }
    })

    const computeScore = (pos) => {
        return 0;
    }
    const fillTable = ()=> {
        $('#datatab > tr').remove();
        var html = '';
        for (let user in Object.keys(guesses))
            html += '<tr><td>' + user + '</td><td>' + computeScore(guesses[user]) + '</td></tr>';
        $('#datatab').html(html);
    }

    const refreshUI = () => {
    }

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

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

            console.log(message.eventType, message.data)
            if(message.eventType == 'follow') {
            } else if(message.eventType == 'subscribe') {
            }
            refreshUI();
        } catch (ex) {
            console.log(ex)
        }
    };


    jQuery(async ()=>{
        refreshUI();
        try{
            socket.addFamilyHandler("chatguessr", handleSocketMessage);
            if(socket){
                while(socket.getReadyState() === 0){
                    await new Promise(r => setTimeout(r, 500));
                }
            }
        }catch(e) {console.log(e)}
    })

});

const calculateScale = (bounds) => haversineDistance({ lat: bounds.min.lat, lng: bounds.min.lng }, { lat: bounds.max.lat, lng: bounds.max.lng }) / 7.458421;
const haversineDistance = (mk1, mk2) => {
		const R = 6371.071;
		const rlat1 = mk1.lat * (Math.PI / 180);
		const rlat2 = mk2.lat * (Math.PI / 180);
		const difflat = rlat2 - rlat1;
		const difflon = (mk2.lng - mk1.lng) * (Math.PI / 180);
		const km = 2 * R * Math.asin(Math.sqrt(Math.sin(difflat / 2) * Math.sin(difflat / 2) + Math.cos(rlat1) * Math.cos(rlat2) * Math.sin(difflon / 2) * Math.sin(difflon / 2)));
		return km;
};
const calculateScore = (distance, scale) => Math.round(5000 * Math.pow(0.99866017, (distance * 1000) / scale));