import { TableroEditor, TableroAtaque ,TableroVisor } from './tablero.js';
const barcosImg = new Image();
barcosImg.src = '/assets/barcos.png';

barcosImg.onload = function () {
  iniciaJuego();
};

function getSprites(spriteSheet) {
  const sprites = {
    PORTAAVIONES: [
      { x: 0, y: 0, width: 64, height: 256 },
      { x: 64, y: 192, width: 256, height: 64 },
    ],
    ACORAZADO: [
      { x: 64, y: 0, width: 64, height: 192 },
      { x: 128, y: 128, width: 192, height: 64 },
    ],
    DESTRUCTOR: [
      { x: 128, y: 0, width: 64, height: 128 },
      { x: 192, y: 64, width: 128, height: 64 },
    ],
    FRAGATA: [
      { x: 192, y: 0, width: 64, height: 64 },
      { x: 256, y: 0, width: 64, height: 64 },
    ],

    OCEANO: [
      { x: 320, y: 0, width: 32, height: 32 },
      { x: 384, y: 0, width: 32, height: 32 },
      { x: 416, y: 0, width: 32, height: 32 },
      { x: 320, y: 32, width: 32, height: 32 },
      { x: 352, y: 64, width: 32, height: 32 },
      { x: 416, y: 64, width: 32, height: 32 },
      { x: 320, y: 96, width: 32, height: 32 },
      { x: 352, y: 96, width: 32, height: 32 },
      { x: 416, y: 96, width: 32, height: 32 },

      { x: 448, y: 0, width: 32, height: 32 },
      { x: 512, y: 0, width: 32, height: 32 },
      { x: 544, y: 0, width: 32, height: 32 },
      { x: 448, y: 32, width: 32, height: 32 },
      { x: 480, y: 64, width: 32, height: 32 },
      { x: 544, y: 64, width: 32, height: 32 },
      { x: 448, y: 96, width: 32, height: 32 },
      { x: 480, y: 96, width: 32, height: 32 },
      { x: 544, y: 96, width: 32, height: 32 },

      { x: 576, y: 0, width: 32, height: 32 },
      { x: 640, y: 0, width: 32, height: 32 },
      { x: 672, y: 0, width: 32, height: 32 },
      { x: 576, y: 32, width: 32, height: 32 },
      { x: 608, y: 64, width: 32, height: 32 },
      { x: 672, y: 64, width: 32, height: 32 },
      { x: 576, y: 96, width: 32, height: 32 },
      { x: 608, y: 96, width: 32, height: 32 },
      { x: 672, y: 96, width: 32, height: 32 },
    ],
  };

  const spritesObj = {};
  const canvas = document.createElement('canvas');
  const ctx = canvas.getContext('2d');
  for (const key in sprites) {
    if (Object.hasOwnProperty.call(sprites, key)) {
      const spriteArray = sprites[key];
      spritesObj[key] = spriteArray.map((sprite) => {
        canvas.width = sprite.width;
        canvas.height = sprite.height;
        ctx.clearRect(0, 0, canvas.width, canvas.height);
        ctx.drawImage(
          spriteSheet,
          sprite.x,
          sprite.y,
          sprite.width,
          sprite.height,
          0,
          0,
          sprite.width,
          sprite.height,
        );
        const spriteImage = new Image();
        spriteImage.src = canvas.toDataURL();
        return spriteImage;
      });
    }
  }
  return spritesObj;
}

function iniciaJuego() {
  const canvasMapa = document.getElementById('mapa');
  const canvasMiniMapa = document.getElementById('minimapa');
  const sprites = getSprites(barcosImg);

  const urlParams = new URLSearchParams(window.location.search);
  const gameId = urlParams.get('game_id');
  const userId = localStorage.getItem('userId');

  const socket = io('/batalla', {
    closeOnBeforeunload: true,
    auth: { userId, gameId },
  });

  let tablero = null;

  const OnChangeState = (snapshotJugador) => {
    console.log(snapshotJugador);
    switch (snapshotJugador.estado) {
      case 'ENPREPARACION':
        ENPREPARACION(snapshotJugador);
        break;
      case 'ENESPERA':
        ENESPERA(snapshotJugador);
        break;
    }
  };

  const handlers = {
    connect: () => {
      gameLoop();
    },
    disconnect: () => {
      window.close();
    },

    OnChangeState,
  };

  Object.entries(handlers).forEach(([event, handler]) => {
    socket.on(event, handler);
  });

  const ENPREPARACION = (snapshotJugador) => {
    muestraBoton('Fijar Flota',()=>{
      socket.emit('setFlota', tablero.mapaFlota.barcos,handlers.OnChangeState);
    });
    addMsgChat('Situa tu flota en el mapa y pulsa el boton para continuar');
    tablero = new TableroEditor(canvasMapa, canvasMiniMapa, sprites, [
      snapshotJugador.mapaFlota,
      snapshotJugador.mapaDeAtaques,
    ]);
  };

  const ENESPERA = (snapshotJugador) => {
    muestraAviso('Espera')
    addMsgChat('Espera mientras el rival acaba de colocar sus tropas');
    tablero = new TableroVisor(canvasMapa, canvasMiniMapa, sprites, [
      snapshotJugador.mapaFlota,
      snapshotJugador.mapaDeAtaques,
    ]);
  };

  function addMsgChat(msg) {
    const divChat = document.querySelector('#logchat');
    const pMsg = document.createElement('p');
    pMsg.textContent = msg;
    divChat.appendChild(pMsg);
    divChat.scrollTop = divChat.scrollHeight;
  }
  function muestraBoton(msg, callback) {
    const divContent = document.querySelector('.div4');
    divContent.innerHTML = `<button class="button button-orange prepasradoBtn"> --${msg}-- </button>`;
    const preparadoBtn = divContent.querySelector('.prepasradoBtn');
    preparadoBtn.addEventListener('click', callback);
  }
  function muestraAviso(msg) {
    const divContent = document.querySelector('.div4');
    divContent.innerHTML = `<span class="avisoMsg parpadea"> -- ${msg} -- </span>`;
  }
  function limpiaContenedorAvisos() {
    const divContent = document.querySelector('.div4');
    divContent.innerHTML = '';
  }

  function gameLoop() {
    if (tablero) tablero.draw();
    window.requestAnimationFrame(gameLoop);
  }
}
