const cbor = require('borc');

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

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

const SOCKET_URL = process.env.NODE_ENV === 'production' ? 'wss://mnml.gg/api/ws' : 'ws://localhost/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(['DevResolve', { a, b, skill }]);
    }

    function onDevResolutions(newRes) {
        const { game, account, animating } = store.getState();

        if (animating) return false;
        store.dispatch(actions.setAnimating(true));
        // stop fetching the game state til animations are done
        return eachSeries(newRes, (r, cb) => {
            if (['Disable', 'TargetKo'].includes(r.event[0])) return cb();

            // convert server enum into anims keywords
            // todo make serersideonly
            const sequence = animations.getSequence(r);
            const timeout = animations.getTime(sequence);
            const anims = animations.getObjects(r, sequence, game, account);
            const text = animations.getText(r, sequence);
            store.dispatch(actions.setAnimFocus(animations.getFocusTargets(r, game)));

            if (sequence.includes('START_SKILL') && anims.animSource) store.dispatch(actions.setAnimSource(anims.animSource));
            if (sequence.includes('END_SKILL') && anims.animTarget) {
                store.dispatch(actions.setAnimTarget(anims.animTarget));
                if (!['Banish', 'Invert'].includes(removeTier(anims.animTarget.skill))) store.dispatch(actions.setAnimCb(cb));
            }
            if (sequence.includes('POST_SKILL' && text)) {
                // timeout to prevent text classes from being added too soon
                setTimeout(
                    () => store.dispatch(actions.setAnimText(text)),
                    timeout - TIMES.POST_SKILL_DURATION_MS
                );
            }
            return setTimeout(() => {
                store.dispatch(actions.setAnimSource(null));
                store.dispatch(actions.setAnimTarget(null));
                store.dispatch(actions.setAnimText(null));
                store.dispatch(actions.setAnimFocus([]));
                if (!sequence.includes('END_SKILL')
                    || ['Banish', 'Invert'].includes(removeTier(anims.animTarget.skill))) return cb();
                return true;
            }, timeout);
        }, err => {
            if (err) return console.error(err);
            // clear animation state
            store.dispatch(actions.setAnimSource(null));
            store.dispatch(actions.setAnimTarget(null));
            store.dispatch(actions.setAnimText(null));
            store.dispatch(actions.setAnimating(false));

            store.dispatch(actions.setSkip(false));

            // set the game state so resolutions don't fire twice
            store.dispatch(actions.setGame(game));
            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);
        // if (res.err) return errHandler(res.err);

        const [msgType, params] = res;
        if (msgType !== 'Pong') console.log(res);

        // check for error and split into response type and data
        if (!handlers[msgType]) return console.error(`${msgType} handler missing`);
        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;
