<template>
  <div class="column is-one-third-desktop">
    <div id="sidebar" class="card">
      <header id="sidebar-heading" class="card-header">
        <p class="card-header-title">
          {{ app_state.initiated ? player.name : "..." }}</p>
        <div class="dropdown is-right"
            :class="{ 'is-active': show_dropdown }">
          <div class="dropdown-trigger" ref="dropdown_btn">
            <a id="change_player" class="card-header-icon"
               @click="show_dropdown = !show_dropdown"
               aria-haspopup="true" aria-controls="dropdown-menu">
              <span class="icon is-small">
                <i class="fas fa-exchange-alt"></i>
              </span>
            </a>
          </div>
          <div class="dropdown-menu" id="dropdown-menu" role="menu"
            v-closable="{ exclude: ['dropdown_btn'], handler: 'closeDropdown', visible: show_dropdown }">
            <div class="dropdown-content" v-if="app_state.initiated">
              <a v-for="(p,i) in app_state.player_list" :key="i"
                 @click="setActivePlayer(i)" 
                 href="#" class="dropdown-item">
                {{ p.name }}</a>
              </div>
            </div>
          </div>
        </header>
      <div class="card-content">
      <Wealth :wealth="wealth" :debt="player.debt"></Wealth>
      <div class="box is-shadowless" v-show="!playerIsGroup">
      	 <div class="columns is-vcentered" @click="switchPlayerChestVisibility">
      	   <div class="column is-one-fifth">
		<span class="icon is-large">
		<i class="fas fa-2x fa-box"></i>
		</span>
	   </div>
	   <div class="column if-four-fifth has-text-left">
	     <p class="is-size-3">Coffre</p>
	   </div>
	 </div>
      </div>
	 <Chest :player="app_state.player_id"
	   v-show="app_state.show_player_chest">
	   </Chest>
      <a href="#" class="button is-link is-fullwidth is-hidden" disabled>Historique</a>
      </div>
    </div>
  </div>
</template>

<script>
    import { AppStorage } from '../AppStorage'
    import Chest from './Chest.vue'
    import Wealth from './Wealth.vue'
    /*
    The Player control board.
    To test :
        - Player name is displayed
        - Player's wealth is displayed -> Inside Wealth component
        - Dropdown:
            - The first item is the group
            - Opened by activator
            - Closed when clicked outside
            - Click on item does switch active player
        - Switch player :
            - Name is updated when player_id is updated
            - Wealth is updated -> Inside Wealth component
        - Chest button controls Chest visibility
            
    */
    let handleOutsideClick;
    export default {
        components: { Chest, Wealth },
        data () {
            return {
                app_state: AppStorage.state,
                show_dropdown: false,
                edit_wealth: false,
                handleOutsideClick: null,
            };
        },
        computed: {
            player () {
            	if (!this.app_state.initiated) return {}
                const idx = this.app_state.player_id;
                return this.app_state.player_list[idx];
            },
            wealth () {
            	if (!this.app_state.initiated) {
            	    return ["-", "-", "-", "-"];
            	} else {
		    const cp = this.player.cp
		    const sp = this.player.sp
		    const gp = this.player.gp
		    const pp = this.player.pp
		    return [cp, sp, gp, pp];
		}
            },
            // Check if the active player is the special 'Group' player
            playerIsGroup () {
                return this.app_state.player_id == 0;
            }
        },
        methods: {
            switchPlayerChestVisibility () {
                AppStorage.switchPlayerChestVisibility();
            },
            hidePlayerChest () {
                if (this.app_state.show_player_chest) {
                    this.switchPlayerChestVisibility();
                }
            },
            setActivePlayer (playerIdx) {
            	var playerIdx = Number(playerIdx);
                AppStorage.setActivePlayer(playerIdx);
                if (playerIdx == 0) { this.hidePlayerChest() }
            },
            closeDropdown () {
                this.show_dropdown = false
            }
        },
        directives: {
            'closable': {
                bind: function(el, binding, vnode) { 
                    handleOutsideClick = (e) => {
                        e.stopPropagation();
                        const { exclude, handler } = binding.value;
                        let excludedElClicked = false;
                        exclude.forEach(refName => {
                            if (!excludedElClicked) {
                                const elt = vnode.context.$refs[refName];
                                excludedElClicked = elt.contains(e.target);
                            }
                        });
                    
                        if (!excludedElClicked) {
                            console.log('outsideCloseDropdown');
                            vnode.context[handler]()
                        }
                    };
                },
                // Bind custom handler only when dropdown is visible
                update: function(el, binding, vnode, _) {
                    const { visible } = binding.value;
                    if (visible) {
                        document.addEventListener('click', handleOutsideClick);
                        document.addEventListener('touchstart', handleOutsideClick);
                    } else {
                        document.removeEventListener('click', handleOutsideClick);
                        document.removeEventListener('touchstart', handleOutsideClick);
                    }
                },
                unbind: function() { console.log("unbind"); 
                    document.removeEventListener('click', handleOutsideClick);
                    document.removeEventListener('touchstart', handleOutsideClick);
                }
            }
        }
    }
</script>

<style scoped>
  .fa-exchange-alt.disabled { opacity: 0.4; }
</style>
