const express = require('express')
var session = require('express-session');
const app = express()
const port = 3000
var { Liquid } = require('liquidjs');
var engine = new Liquid();
const path = require('path');
const bodyParser = require("body-parser");
const game = require('./game.js');
const { Player } = require('./user.js');

/*  WEBSOCKETS */
const httpServer = require("http").createServer(app);
const options = { /* ... */ };
const io = require("socket.io")(httpServer, options);

/*  VIEWS      */
app.engine('liquid', engine.express()); 
app.set('views', ['./views', './views/layouts']);            // specify the views directory
app.set('view engine', 'liquid');       // set liquid to default

/* RESSOURCES  */
app.use(express.static(path.join(__dirname, '/ressources')));

/* FORMS       */
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());

/* SESSIONS    */
app.use(session({secret: "Shh, its a secret!"}));

let waitingPseudo = "";
let i = 0;
let rooms = []

function getChamber(name) {
  for (let i of rooms) {
    if (i.name == name) {
      return i;
    }
  } //TODO lors de la recherche db faire une recherche WHERE id == username
  return undefined;
}

function pioche(deck) {
  return deck.shift();
}

io.on("connection", socket => {
  socket.on("wait", (arg) => {
    // console.log('toto', arg);
    socket.pseudo = arg.pseudo;
    if (waitingPseudo == "") {
      waitingPseudo = arg.pseudo; //on dit que quelqu'un attends
      socket.join("room" + i); //on rejoint la salle;
    } else {
      waitingPseudo = "" //on réinitialise
      socket.join("room" + i);  //on rejoint la salle
      io.to("room" + i).emit("both_here", "room" + i); //on emit qu'on a deux joueurs
      i++; //on rajoute 1 à i
    }
  });

  socket.on("here", (arg) => {
    socket.join(arg.room);
    let players = Array.from(io.sockets.adapter.rooms.get(arg.room));
    if (players.length == 1) {
      rooms.push({
        name : arg.room,
        players : [new Player(socket.id)],
        currentlyPlaying : socket.id,
        actions : [{}, {}]
      })
    }
    if (players.length == 2) {
      chamber = getChamber(arg.room);
      player = new Player(socket.id)
      player.getCartes();
      chamber.players[0].getCartes();
      chamber.players.push(player)//On crée un nouveau player
      io.to(players[0]).emit("begin", { pv : player.point_de_vie, cartes: chamber.players[0].cartes_en_main, cartes_ennemies: player.cartes_en_main, prochaine : chamber.players[0].deck[0] }) //tu commences
      io.to(players[1]).emit("deck", { pv : player.point_de_vie, cartes: player.cartes_en_main, cartes_ennemies: chamber.players[0].cartes_en_main, prochaine : player.deck[0] }) //tu attends ton tour (on va renvoyer un emit pour créer ce player)
    }
  })


  socket.on("skip", (arg) => {
    chamber = getChamber(arg.room);
    if (socket.id == chamber.currentlyPlaying) {
      chamber.currentlyPlaying = chamber.players[(chamber.players.findIndex((player) => player.id==socket.id) + 1) % 2].id
      socket.to(chamber.name).emit("your_turn");
    } else {
      console.log(socket.id, chamber.currentlyPlaying)
      socket.emit("error")
    }
  });

  socket.on("pose_creature", (arg) => {
    chamber = getChamber(arg.room);
    if (socket.id == chamber.currentlyPlaying) {
      player = chamber.players[chamber.players.findIndex((player) => player.id==socket.id)];
      if (player.cartes_en_main.findIndex((carte) => carte.name == arg.carte.name) != -1) { //Si on a bien la carte en main
        if (Object.keys(player.monsters[arg.index]).length == 0) {
          player.monsters[arg.index] = arg.carte;
          socket.to(chamber.name).emit("pose_creature", arg);
        }
      }
    }
  });
  socket.on("pose_AC", (arg) => {
    chamber = getChamber(arg.room);
    if (socket.id == chamber.currentlyPlaying) {
      player = chamber.players[chamber.players.findIndex((player) => player.id==socket.id)];
      if (player.cartes_en_main.findIndex((carte) => carte.name == arg.carte.name) != -1) {
        if (Object.keys(chamber.actions[arg.index]).length != 0) { //si on a déjà une carte action sur l'emplacement
          chamber.player[chamber.actions.proprietaire].defausse.push(chamber.actions[arg.index]) //on met l'ancienne dans la défausse du proprio
        }
        chamber.actions[arg.index] = arg.carte;
        socket.to(chamber.name).emit("pose_AC", arg);
      }
    }
  });

  socket.on("pioche", (arg) => {
    chamber = getChamber(arg.room);
    player = chamber.players[chamber.players.findIndex((player) => player.id==socket.id)];
    carte = pioche(player.deck); //On pioche la carte
    player.cartes_en_main.push(carte) //on la met dans la main
    socket.emit("pioche", {carte : carte, prochaine : player.deck[0]}) //on envoie la donnée
    socket.to(chamber.name).emit("ennemy_pioche", {carte : carte}) //On dit à l'autre qu'on a pioché
  })
});



app.get('/', (req, res) => {
  // res.render('accueil');
  res.send('Hello World!')
})
app.get('/home', (req, res) => {
  res.render('accueil');
})
app.post('/wait', (req, res) => {
  pseudo = req.body.pseudo;
  res.render('waitingRoom', {pseudo : req.body.pseudo});
})

app.post('/game', (req, res) => {
  res.render('game', { room : req.body.room, pseudo : req.body.pseudo })
})

// app.listen(port, () => {
//   console.log(`Example app listening on port ${port}`)
// })
httpServer.listen(3000, () => {
  console.log("coonect");
});