const cbor = require('borc');

const toast = require('izitoast');
const eachSeries = require('async/eachSeries');

const actions = require('./actions');
const { TIMES } = require('./constants');
const { getCombatSequence } = require('./utils');

const SOCKET_URL = process.env.NODE_ENV === 'production' ? 'wss://mnml.gg/api/ws' : 'ws://localhost:40000/api/ws';

function createSocket(store) {
    let ws = null;
    // -------------
    //   Outgoing
    // -------------
    function send(msg) {
        if (msg.method !== 'ping') console.log('outgoing msg', msg);
        ws.send(cbor.encode(msg));
    }

    function sendDevResolve(a, b, skill) {
        send({ method: 'dev_game_resolve', params: { a, b, skill } });
    }

    function onDevResolutions(newRes) {
        const { game: currentGame } = store.getState();
        return eachSeries(newRes, (r, cb) => {
            if (['Disable', 'TargetKo'].includes(r.event[0])) return cb();
            // Create sub events for combat animations
            const sequence = getCombatSequence(r);
            return eachSeries(sequence, (stages, sCb) => {
                const stagedR = Object.create(r);
                stagedR.stages = stages;
                let timeout = 0;
                if (stages.includes('START_SKILL') && stages.includes('END_SKILL')) {
                    timeout = (TIMES.TARGET_DURATION_MS + TIMES.TARGET_DELAY_MS);
                } else if (stages.includes('START_SKILL')) timeout = TIMES.SOURCE_DURATION_MS;
                else if (stages.includes('END_SKILL')) timeout = TIMES.TARGET_DURATION_MS;
                else if (stages.includes('POST_SKILL')) timeout = TIMES.POST_SKILL_DURATION_MS;
                store.dispatch(actions.setResolution(stagedR));

                return setTimeout(sCb, timeout);
            }, err => {
                if (err) console.error(err);
                // Finished this resolution
                return cb();
            });
        }, err => {
            if (err) return console.error(err);
            store.dispatch(actions.setResolution(null));
            // stop skipping resolutions
            store.dispatch(actions.setSkip(false));
            // update the game
            store.dispatch(actions.setGame(currentGame));
            return true;
        });

    }

    const handlers = {
        DevResolutions: onDevResolutions,
    };

    // decodes the cbor and
    // calls the handlers defined above based on message type
    function onMessage(event) {
        // decode binary msg from server
        const blob = new Uint8Array(event.data);
        const res = cbor.decode(blob);
        const [msgType, params] = res;
        if (!handlers[msgType]) return false;
        return handlers[msgType](params);
    }

    // Connection opened
    function onOpen() {
        toast.info({
            message: 'connected',
            position: 'topRight',
        });
        return true;
    }

    function onError(event) {
        console.error('WebSocket error', event);
    }

    function onClose(event) {
        console.error('WebSocket closed', event);
        toast.warning({
            message: 'disconnected',
            position: 'topRight',
        });
        return setTimeout(connect, 5000);
    }

    function connect() {
        if (ws) {
            ws.removeEventListener('open', onOpen);
            ws.removeEventListener('message', onMessage);
            ws.removeEventListener('error', onError);
            ws.removeEventListener('close', onClose);
            ws = null;
        }

        ws = new WebSocket(SOCKET_URL);
        ws.binaryType = 'arraybuffer';

        // Listen for messages
        ws.addEventListener('open', onOpen);
        ws.addEventListener('message', onMessage);
        ws.addEventListener('error', onError);
        ws.addEventListener('close', onClose);
        return ws;
    }

    return {
        sendDevResolve,
        connect,
    };
}

module.exports = createSocket;
