<template>
  <div>
    <b-navbar toggleable="lg" type="dark" variant="info">
      <b-navbar-brand>
        <router-link to="/" class="text-white ">MPower PS-API</router-link>
      </b-navbar-brand>

      <b-navbar-toggle target="nav-collapse"></b-navbar-toggle>

      <b-collapse id="nav-collapse" is-nav class="main-header">
        <b-navbar-nav v-if="loggedInUser">
          <b-nav-item>
            <span @click="$router.history.push(`/grabbers`)" class="text-white ">Grabbers</span>
          </b-nav-item>
          <b-nav-item>
            <b-dropdown text="Suppliers">
              <div class="p-2"><b-form-input v-model="search"></b-form-input></div>
              <div style="max-height: 250px; overflow-y: auto;">
                <b-dropdown-item
                  v-for="item in list"
                  target="_blank"
                  :href="`/new-portal?token=${item.tokens[0]}`"
                  @click="moveTo(item)"
                >
                  {{ item.name }}
                </b-dropdown-item>
              </div>
            </b-dropdown>
          </b-nav-item>
        </b-navbar-nav>

        <!-- Right aligned nav items -->
        <b-navbar-nav class="ml-auto">
          <b-nav-item-dropdown right v-if="loggedInUser">
            <template v-slot:button-content>
              <em>User</em>
            </template>
            <b-dropdown-item @click="$store.dispatch('auth_logout')">Sign Out</b-dropdown-item>
          </b-nav-item-dropdown>
          <router-link to="/signin" v-else>
            <b-button size="sm" class="my-2 my-sm-0">Log IN </b-button>
          </router-link>
        </b-navbar-nav>
      </b-collapse>
    </b-navbar>
    <router-view></router-view>
  </div>
</template>

<script>
module.exports = {
  data() {
    return {
      search: ""
    };
  },
  mounted() {
    if (location.href.match("/new-portal")) {
    } else {
      this.$store.dispatch("get_user");
    }

    document.title = "MPower Grabber(s)";
  },

  computed: {
    suppliers() {
      return this.$store.getters["suppliers"];
    },
    list() {
      if (this.search) {
        return this.suppliers.filter(item => item.name.toLowerCase().includes(this.search.toLowerCase()));
      }
      return this.suppliers;
    }
  },
  methods: {
    moveTo(item) {
      location.href = `/new-portal?token=${item.tokens[0]}`;
    }
  }
};
</script>

<style>
.main-header .navbar-nav li {
  display: flex;
  align-items: center;
}
</style>
