/**
 * Created by rockyl on 2019-12-25.
 */

import io from 'socket.io-client';
import events from './global-events';

let socket;

export let codeSyncServeEnabled = false;
export let codeSyncServeConnected = false;

export function startCodeSyncServe(config) {
	if (socket) {
		socket.close();
	}

	socket = io(`http://${config.ip}:${config.port}`);
	socket.on('connect', onConnect);
	socket.on('disconnect', onDisconnect);
	socket.on('edit-save', onEditSave);

	events.$on('edit-open', editCode);

	codeSyncServeEnabled = true;
	events.$emit('code-sync-status', true);
}

export function stopCodeSyncServe() {
	if (socket) {
		socket.close();
	}

	codeSyncServeEnabled = false;
	events.$emit('code-sync-status', false);
}

export function editCode(code) {
	if (socket && socket.connected) {
		socket.emit('edit-open', code);
	}
}

function onConnect(t) {
	codeSyncServeConnected = true;
	events.$emit('code-sync-start');
}

function onDisconnect() {
	codeSyncServeConnected = false;
	events.$emit('code-sync-stop');
}

function onEditSave(data) {
	events.$emit('edit-save', data)
}
