'use strict';
import io from 'socket.io-client';

const SERVER_URL = 'http://' + process.env.VUE_APP_SERVER_HOST;
const SERVER_PORT = process.env.VUE_APP_SERVER_PORT;

export default function SocketService(socketEventBus) {
  let eventBus = socketEventBus;
  let ioClient = null;
  let connect = function(name) {
    let promise = new Promise((resolve, reject) => {
      console.log(
        'Connecting socket service to : ' + SERVER_URL + ':' + SERVER_PORT
      );
      ioClient = io(SERVER_URL + ':' + SERVER_PORT, {
        reconnectionAttempts: 2
      });

      ioClient.on('disconnect', reason => {
        if (reason !== 'io client disconnect') {
          console.log('Connection with server lost unexpectidly : ' + reason);
          // this.ioClient.close();
        }
      });

      ioClient.on('connect', () => {
        console.log('Connected to server');
        ioClient.emit('auth', name, function(response) {
          if (response.res === 'ok') {
            resolve(response.message);
          } else {
            reject(response.message);
          }
        });
      });

      ioClient.on('connect_error', () => {
        console.log('connect_error to server');
      });

      ioClient.on('reconnect_failed', () => {
        console.log('reconnect_failed to server');
        reject(new Error('Cannot reach server'));
      });

      ioClient.on('reload-games-list', () => {
        console.log('force reload games list !');
        eventBus.$emit('reload-games');
      });
    });
    return promise;
  };

  let checkConnection = function(playername) {
    if (ioClient && ioClient.connected === false) {
      return connect(playername);
    } else {
      return Promise.resolve('Still connected');
    }
  };

  let disconnect = function() {
    console.log('Manual client disconnect');
    ioClient.close();
  };
  let getGamesList = function(playername) {
    return checkConnection(playername).then(
      () => {
        return new Promise((resolve, reject) => {
          ioClient.emit('games-list', playername, function(response) {
            if (response.res === 'ok') {
              resolve(response.message);
            } else {
              reject(response.message);
            }
          });
        });
      },
      error => Promise.reject(error)
    );
  };

  let createGame = function(game) {
    return checkConnection(game.player1).then(
      () => {
        return new Promise((resolve, reject) => {
          ioClient.emit('create-game', game, function(response) {
            if (response.res === 'ok') {
              resolve(response.message);
            } else {
              reject(response.message);
            }
          });
        });
      },
      error => Promise.reject(error)
    );
  };
  let removeCreatedGames = function(username) {
    return checkConnection(username).then(
      () => {
        return new Promise(resolve => {
          console.log('emit : remove-created-game');
          ioClient.emit('remove-created-game', username, function(response) {
            resolve(response);
          });
        });
      },
      error => Promise.reject(error)
    );
  };
  return {
    connect,
    disconnect,
    getGamesList,
    createGame,
    removeCreatedGames
  };
}
