<template>
  <main id="app" class="section">
  <section id="content" class="columns is-desktop">
    <Player></Player>
    <div class="column">
      <GroupChest></GroupChest>
    </div>
  </section>
  </main>
</template>

<script>
import Player from './components/Player.vue'
import GroupChest from './components/GroupChest.vue'

export const store = {
    debug: true,
    state: {
        player_id: 0,
        player_list: [
            {id: 0, name: "Groupe", wealth: [0,0,0,0], debt: 0},
            {id: 1, name: "Lomion", wealth: [0,0,0,0], debt: 0},
            {id: 4, name: "Oilosse", wealth: [0,0,0,0], debt: 0},
            {id: 3, name: "Fefi", wealth: [0,0,0,0], debt: 0},
        ],
        show_player_chest: false,
        requests: {  // TEST: must be initialised with players ids
            0: [], 1: [], 4: [], 3: []
        },
    },
    setActivePlayer (newPlayerId) {
        if (this.debug) console.log('setActivePlayer to ', newPlayerId)
        this.state.player_id = newPlayerId
        document.cookie = `player_id=${newPlayerId};`;
    },
    switchPlayerChestVisibility () {
        if (this.debug) console.log('switchPlayerChestVisibility', !this.state.show_player_chest)
        this.state.show_player_chest = !this.state.show_player_chest
    },
    putRequest (itemId) {
        const playerId = this.state.player_id
        if (this.debug) console.log('newRequest from', playerId, 'on', itemId)
        this.state.requests[playerId].push(itemId);
    },
    cancelRequest(itemId) {
        const playerId = this.state.player_id
        if (this.debug) console.log('cancelRequest of', playerId, 'on', itemId)
        var idx = this.state.requests[playerId].indexOf(itemId);
        if (idx > -1) {
            this.state.requests[playerId].splice(idx, 1);
        } else {
            if (this.debug) console.log("cancel a non-existent request")
        }
    }
}

function getCookie(cname) {
  var name = cname + "=";
  var decodedCookie = decodeURIComponent(document.cookie);
  var ca = decodedCookie.split(';');
  for(var i = 0; i <ca.length; i++) {
    var c = ca[i];
    while (c.charAt(0) == ' ') {
      c = c.substring(1);
    }
    if (c.indexOf(name) == 0) {
      return c.substring(name.length, c.length);
    }
  }
  return "";
}

export default {
  name: 'app',
  components: {
    Player,
    GroupChest
  },
  created () {
    const cookie = getCookie("player_id");
    if (cookie == "") {
        return;
    } else {
        var newPlayerId = Number(cookie);
        console.log("initiated with id", newPlayerId); 
        store.setActivePlayer(newPlayerId);
    }
  }
}
</script>

<style>
#app {
  font-family: 'Avenir', Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
</style>
