import io from 'socket.io-client';
import { set_socket, set_user } from './Store_chat';
import { socket_events } from './Socket_events';

const address = `http://${process.env.WEBSITE_HOST}:${process.env.WEBSITE_PORT}`;

export async function init_socket()
{
	const response = await fetch(`${address}/api/v2/user`);
	const response_data = await response.json();

	set_user(response_data);

	let socket = await io(address,
	{
		path: '/chat',
		query:
		{
			username: response_data.username,
		},
	});
	set_socket(socket);

	socket.on('connect',           function(){ console.log("socket.io connected"); });
	socket.on('disconnect',        function(){ console.log("socket.io disconnected"); });
	socket.on('connect_error',     function(){ console.log("socket.io connect_error"); });
	socket.on('connect_timeout',   function(){ console.log("socket.io connect_timeout"); });
	socket.on('error',             function(){ console.log("socket.io error"); });
	socket.on('reconnect',         function(){ console.log("socket.io reconnect"); });
	socket.on('reconnect_attempt', function(){ console.log("socket.io reconnect_attempt"); });
	socket.on('reconnecting',      function(){ console.log("socket.io reconnecting"); });
	socket.on('reconnect_error',   function(){ console.log("socket.io reconnect_error"); });
	socket.on('reconnect_failed',  function(){ console.log("socket.io reconnect_failed"); });
	socket.on('ping',              function(){ console.log("socket.io ping"); });
	socket.on('pong',              function(){ console.log("socket.io pong"); });

	socket_events(socket);
}

