'use strict';
import io from 'socket.io-client';
// import promiseTimeout from './utils/promise-timeout';
/*
  Messages :
    - disconnect
    - reconnecting
    - reconnect
    - reconnect_failed
    -
*/
const SERVER_URL = 'http://' + process.env.SERVER_HOST;
const SERVER_PORT = process.env.SERVER_PORT;



export default class SocketService {
  constructor() {
    this.lostConnectionListeners = new Set();
  }

  addlostConnectionListener(listener) {
    this.lostConnectionListeners.add(listener);
  }


  removelostConnectionListener(listener) {
    this.lostConnectionListeners.delete(listener);
  }

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

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

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

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

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

    });
    return promise;
  }

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

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

  createGame(game){
    return this.checkConnection(game.player1).then( () => {
      return new Promise( (resolve, reject) => {
        this.ioClient.emit('create-game', game, function (response) {
          if (response.res === "ok") {
            resolve(response.message);
          } else {
            reject(response.message);
          }
        });
      });
    },
    (error) => Promise.reject(error));
  }
}
