<template>
  <div class="w-100 h-auto p-r b-we">
    <!-- NAVIGATION Bar -->
    <div class="w-100 h-auto d-fx jc-c p-r" :class="{'bo_b-1px bo-F4F4F4': self.$route.meta.header_border_bottom}">
      <div class="w-100 xw-1200px h-75px pl-15px pr-15px d-fx jc-sb p-r">
        <!-- LOGO -->
        <div ref="logo" class="h-100 d-fx jc-c ai-c ">
          <button class="h-100 d-fx jc-c ai-c" @click="goHome">
            <div class="h-100 cursor-pointer d-fx jc-c ai-c">
              <div class="w-100">
                <i :class="`icon-${this.site.en} c-${this.colors[`${this.logo_color}`]} f-${logo_size}px l-_${negative_left_align}px`" class="f-38px"></i>
              </div>
            </div>
          </button>
        </div>
        <!-- MENU -->
        <div ref="menu" class="xw-1083px w-100 h-100 p-r">
          <div class="h-100 d-fx jc-sb ai-c" v-if="menus_now" >
            <div> 
              <div class="d-fx ai-c" v-if="this.$route.meta.header_menus">
                <!-- :class="menu_index == menu.length - 1 ? 'b-rd' : 'b-we'" -->
                <header-button-c class="" @click="updateMenuClicked()"
                  :class="[(menu_index === 0 ? 'ml-0' : 'ml-24px'), (menu_index === menus_now.length - 1 ? 'mr-0' : 'mr-24px')]"
                  v-for="(menu, menu_index) in menus_now" 
                  :key="menu_index" :menu="menu" 
                  :color="color"
                  ></header-button-c>
              </div>
            </div>
            <div class="d-fx ai-c">
              <!-- Right Div/Part of the HEADER -->
              <div class="d-fx ai-c" v-if="this.$route.meta.right_div_component === ''">
                <div :is="this.getCurrRightDiv" v-if="this.$route.meta.header_right_div"></div>
              </div>
              <div is="notSigned" v-else-if="this.id === null"></div>
              <slot v-else></slot>

              <!-- Image Icon --> 
              <div class="w-36px h-36px bor-100 ml-24px p-r o-h cursor-pointer d-fx jc-c ai-c" @click="$store.state.header.option = true" v-if="this.$route.meta.header_img_icon === true && $store.state.auth.id !== null && dataReady">
                <img class="background-size_cover w-36px h-36px " v-if="user_data[0].image" :src="user_data[0].image" alt="">
                <i class="icon-user-circle c-767676 f-27px t-_2px" v-else></i>
              </div>
            </div>
          </div>
          <div>
          </div>
          <!-- NOTIFICATIONS -->
          <transition name="v-fade">
            <div class="w-330px xh-486px p-a r-100px t-70px z-50 bor-6px o-h bs-1_4_14_878E93_20" v-if="this.$store.state.header.notification" v-on-clickaway="toggleNotification">
              <header-notification-c></header-notification-c>
            </div>
          </transition>
          <!-- OPTIONS -->
          <div class="w-240px h-100 p-a r-0 t-70px z-50" v-on-clickaway="toggleOption" v-if="self.$store.state.header.option">
            <nav class="p-r">
              <ul class="b-we bs-2_2_5_D7E0E4_40 d-fx fxd-c ai-c bor-6px p-r bo-1px bo-EDEDED_50">
                <div class="w-192px h-50px d-fx jc-c ai-c bo_b-1px bo-EDEDED_50 mb-10px" v-if="dataReady">
                  <span class="f-14px c-999999 t-c p-r">{{user_data[0].name}}</span>
                </div>
                
                <router-link :to="option.path === '/mypage' ? option.path+`/${$store.state.auth.id}/` : option.path" 
                class="f-14px c-222222 c-FFFFFF-h w-100 h-30px lh-30px bo-gy text_decoration-none c-333333 b-bk-h pl-24px cursor-pointer"
                v-for="(option, option_index) in self.$store.state.header.optionMenus" :key="option_index"
                @click.native="toggleOption">
                  {{option.name}}
                </router-link>

                <div class="h-52px w-192px d-fx ai-c mt-12px bo_t-1px bo-EDEDED_50">
                  <span class="f-14px cursor-pointer c-222222 lh-30px" @click="signOut">Sign Out</span>
                </div>
              </ul>
            </nav>
          </div>
        </div>
      </div>
    </div>
    <!-- SEARCH BAR -->
    <transition name="v-fade">
      <div v-if="self.$store.state.header.searchBox"
      class="w-100 h-149px p-r cen-x pr-15px pl-15px bo_b-1px bo-F4F4F4">
        <input type="text" placeholder="Search Tools Site" class="p-a cen f-42px lh-51px fw-600 c-333333 t-c" v-model="searchValue">
      </div>
    </transition>    

    <!-- {{this.$store.state.header.searchResult}} -->
  </div>
</template>

<script>
import {mapStateVModel} from 'map-state-vmodel';
// mixins
import { mixin as clickaway } from 'vue-clickaway';
import header_search from "@/mixins/auto_imported/header_search.js"
// menus components
import HeaderButtonC from './header/HeaderButtonC.vue';
// right-div components
import notSignedC from './header/signed_and_unsigned/notSignedC.vue'
import signedC from './header/signed_and_unsigned/signedC.vue'
import HeaderNotificationC from './header/right-div/notifications/HeaderNotificationC.vue' 

export default {
  name: 'Ic_header',
  mixins: [ clickaway, header_search],
  extends: {},
  props: { 
    site: Object, 
    menus: Object,
    color: Array, // menu coloring on hover effect
    colors: {
      type: Object, // color choices depending on site
    },
    logo_size: String, // logo height
    negative_left_align: String, // logo width/2
  },
  data() {
    return {
      menus_now: Object, 
      width_search: 0, 
      lang:window.lang, 
      self:this, 
      show: false, 
      publicPath: process.env.BASE_URL,
      user_data: [], // fetched data from userist
      dataReady: false, // true: when user_data are available
      searchValue: '',
      // logo
      // logo_size: '24', // logo height
      // negative_left_align: '39', // logo width/2
    }
  },
  components: {
    'header-button-c':HeaderButtonC,
    'header-notification-c': HeaderNotificationC,
    notSigned: notSignedC,
    signed: signedC
  },
  watch: {
    logo_color() {},
    searchValue() {
      let self = this
      setTimeout(function () {
        self.search(self.searchValue)
      }, 1000);
    }
  },
  computed: {
    ...mapStateVModel('auth', ['id', 'account_id', 'token']),
    ...mapStateVModel('header', ['option']),
  


    // logo_symbol(){
    //   let color = this.$route.name=='Home'?'white':'color';
    //   return `${this.publicPath}images/header/logo_symbol/${color}/${this.site.en}.png`
    // },

    logo_color () {
      let color = this.$route.meta.header_logo_color
      if (color === '') {
        return color = 'first'
      } else {
        return color
      }
    },
    logo_text(){
      let color = this.$route.name=='Home'?'color':'color';
      return `${this.publicPath}images/header/logo_text/${color}/${this.site.en}.png`
    },
    getCurrRightDiv() {
      if(this.id === null) {
        return 'notSigned'
      } else {
        if(this.$route.meta.right_div_component === '') {
          return 'signed'
        } else {
          return null
        }
      }
    },
    getUserIdFromAuth() {
      if(this.$store.state.auth.id) {
        return this.$store.state.auth.id
      }
      return true
    },
    checkSignUserData() {
      if(this.$store.state.sign.user_data[0] !== undefined) {
        return this.setUserData(this.$store.state.sign.user_data)
      }
      return true
    }
  },
  methods: {
    // async search(searchValue){
    //   // console.log('Input Value:' + searchValue);
    //   if (searchValue) {
    //     let { data } = await LeanCanvasM.getParams({ "search": `${searchValue}` })
    //     this.searchResult = await data.results
    //     await console.log(data.results);
    //     // NOTE add the result of this function to store
    //   } else {
    //     this.searchResult = ''
    //   }
    // },
    signOut() {
      this.$router.push({ path: '/'})
      this.id = null
      this.account_id =  null
      this.token =  null
      this.option =  false // option modal
      this.$cookies.remove('token')
    
      const Toast = this.$swal.mixin({ toast: true, position: 'top-end', showConfirmButton: false, timer: 3000})
      Toast.fire({ type: 'success', title: 'Logged out successfully' })
    },
    // Get Function Section
    getMenus:function(){
      let menus = [];
      // menus = window._.concat(menus, this.site.menus, this.menus.signin); // CONCATINATED WITH "SIGN"
      menus = window._.concat(menus, this.site.menus);
      return menus;
    },
    getWidthOfLogo () {
      if(this.$refs.logo) return this.$refs.logo.clientWidth;
      else return 0;
    },
    getWidthOfMenu () {
      if(this.$refs.menu) return this.$refs.menu.clientWidth;
      else return 0;
    },
    // Go Function Section
    goHome:function(){
      if(this.$route.name!='Home'){ 
        this.$router.push({ name: 'Home' }); 
        return; 
      }
    },

    // Set Function Section
    setWidthOfSearch () {
      var self = this;
      var setWidth = function(){
        setTimeout(function(){
          var width_logo = self.getWidthOfLogo();
          var width_menu = self.getWidthOfMenu();
          var margin = 69;
          self.width_search = 'calc(100% - '+(width_logo+width_menu+margin)+'px)';
        }, 500);
      };
      setWidth();

      self.$nextTick(function() {
        window.addEventListener('resize', setWidth);
      })
    },

    async setUserData (data) {
        this.user_data = await data
        this.dataReady = await true
    },

    // Toggle Function Section
    toggleOption () {
      this.$store.state.header.option = false
    },
    toggleNotification () {
      this.$store.state.header.notification = false
    }
  },
  beforeCreate(){},
  beforeUpdate (){
    this.setWidthOfSearch();
  },
  mounted() {
    this.getCurrRightDiv
  },
  created() {
    // For reactivity purposes
    this.$watch('checkSignUserData', () => {
      this.checkSignUserData
    })
    this.menus_now = this.getMenus();
  }
}


/*
  REQUIRED PLUGINS TO INSTALL:
  * VueI18n
  * lodash
  * store
  * router
*/
</script>

<style scoped>
::placeholder { /* Chrome, Firefox, Opera, Safari 10.1+ */
  color: #333333;
  opacity: .2;
}

:-ms-input-placeholder { /* Internet Explorer 10-11 */
  color: #333333;
  opacity: .2;
}

::-ms-input-placeholder { /* Microsoft Edge */
  color: #333333;
  opacity: .2;
}
</style>