<template>
  <PlayerView
    :id="player_id"
    v-slot="{ player, loot, notifications, actions, claims }"
  >
    <main id="app" class="container">
      <header>
        <HeaderBar>
          <template v-slot:title>
            {{ player.name }}
          </template>
          <template v-slot:links>
            <a class="navbar-item">History of Loot</a>
            <template v-if="playerIsGroup">
              <hr class="navbar-divider">
              <div class="navbar-item heading">Admin</div>
              <a class="navbar-item">"Resolve claims"</a>
              <a class="navbar-item">"Add player"</a>
            </template>
            <hr class="navbar-divider">
            <div class="navbar-item heading">Changer</div>
            <a v-for="(p,i) in playerList" :key="i"
              @click="setActivePlayer(i)"
              href="#" class="navbar-item">
              {{ p.name }}</a>
          </template>
        </HeaderBar>
        <Wealth 
            :wealth="[player.cp, player.sp, player.gp, player.pp]" 
            :debt="player.debt"
            @update="actions.updateWealth"
        ></Wealth>
        <p v-show="notifications.length > 0">{{ notifications }}</p>
      </header>
      <nav>
        <div class="tabs is-centered is-boxed is-medium">
          <ul>
            <li :class="{ 'is-active': activeView == 'group' }">
              <a @click="switchView('group')">
                Coffre de groupe
              </a>
            </li>
            <li v-show="!playerIsGroup" :class="{ 'is-active': activeView == 'player' }">
              <a @click="switchView('player')">
                Mon coffre
              </a>
            </li>
            <li :class="{'is-active': activeView == 'adding' }">
              <a class="has-text-grey-light"
                 @click="switchView('adding')">
                + {{ playerIsGroup ? 'Nouveau Loot' : 'Acheter' }}
              </a>
            </li>
           </ul>
        </div>
      </nav>
      <main class="section">
        <template v-if="isAdding">
          <Loot v-if="playerIsGroup"
            :inventory="itemsInventory"
            @addItem="item => pending_loot.push(item)"
            @confirmAction="addNewLoot"
          ></Loot>
          <AddingChest
              :player="player.id"
              :claims="claims"
              :items="playerIsGroup ? pending_loot : itemsInShop"
              :perms="playerIsGroup ? {} : { canBuy: true }"
              @buy="(data) => { switchView('player'); actions.buyItems(data); }">
          </AddingChest>
        </template>
        <Chest v-else
            :player="player.id"
            :claims="claims"
            :items="showPlayerChest ? loot : groupLoot"
            :perms="{ 
                canGrab: !(showPlayerChest || playerIsGroup), 
                canSell: showPlayerChest || playerIsGroup
            }"
            @sell="actions.sellItems"
            @claim="actions.putClaim"
            @unclaim="actions.withdrawClaim">
        </Chest>
      </main>
    </main>
  </PlayerView>
</template>

<script>
import PlayerView from './components/PlayerView.js'
import HeaderBar from './components/HeaderBar.vue'
import Wealth from './components/Wealth.vue'
import Chest from './components/Chest.vue'
import Loot from './components/Loot.vue'
import { api } from './lootalot.js'

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',
  data () {
      return {
        player_id: 0,
        playerList: [],
        activeView: 'group',
        groupLoot: [],
        itemsInventory: [],
        itemsInShop: [{id: 1, name: "Item from shop #1", base_price: 2000}],
        pending_loot: [],
        initiated: false,
      };
  },
  components: {
    PlayerView,
    HeaderBar,
    'AddingChest': Chest, // Alias to prevent component re-use 
    Chest,
    Wealth,
    Loot,
  },
  created () {
      const cookie = getCookie("player_id");
      this.player_id = cookie ? Number(cookie) : 0;
      Promise.all([
          api.fetch("players/", "GET", null),
          api.fetch("players/0/loot", "GET", null),
          api.fetch("items", "GET", null),
      ])
          .then(([players, loot, items]) => {
              this.playerList = players.value;
              this.groupLoot = loot.value;
              this.itemsInventory = items.value;
          })
          .catch(r => alert("Error ! \n" + r))
          .then(() => this.initiated = true);
  },
  methods: {
    setActivePlayer (idx) { 
        if (idx == 0) this.switchView('group');
        this.player_id = Number(idx)
        document.cookie = `player_id=${idx};`;
    },
    switchView (viewId) {
        if (!['group', 'player', 'adding'].includes(viewId)) {
            console.error("Not a valid view ID :", viewId);
        }
        this.activeView = viewId;
    },
    addNewLoot () {
        api.fetch("admin/add-loot", "POST", this.pending_loot)
           .then(() => {
               this.pending_loot = []
               this.switchView('group');
           })
           .catch(r => alert("Error: " + r));
    }
  },
  computed: {
    showPlayerChest () { return this.activeView == 'player' },
    isAdding () { return this.activeView == 'adding' },
    playerIsGroup () { return this.player_id == 0 },
  }
}
</script>

<style scoped>
    header {
        padding-bottom: 1.5em;
    }
</style>
