import { io } from 'socket.io-client';
import { socketio_port } from '../../../../sites/common_site_config.json';
import { getCachedResource, getCachedListResource } from 'jingrow-ui';

export function initSocket() {
	let host = window.location.hostname;
	let siteName = window.site_name;
	let protocol = window.location.protocol.slice(0, -1);
	let port = window.location.port ? `:${socketio_port}` : '';
	let url = `${protocol}://${host}${port}/${siteName}`;

	let socket = io(url, {
		withCredentials: true,
		reconnectionAttempts: 5,
		secure: protocol === 'https'
	});

	socket.on('refetch_resource', data => {
		if (data.cache_key) {
			let resource =
				getCachedResource(data.cache_key) ||
				getCachedListResource(data.cache_key);
			if (resource) {
				resource.reload();
			}
		}
	});
	return socket;
}
