<template>

  <v-app-bar
    app
    clipped-left
    elevation="1"
  >
    <v-img src="/wgp-logo.png"
      contain
      max-height="32px" max-width="32px"
    ></v-img>

    <v-toolbar-title class="mx-2" @click="$router.push('/')" style="cursor: pointer;">Dougal</v-toolbar-title>

    <v-spacer></v-spacer>

    <v-menu bottom offset-y>
      <template v-slot:activator="{on, attrs}">
        <v-hover v-slot="{hover}">
          <v-btn
            class="align-self-center"
            :xcolor="hover ? 'secondary' : 'secondary lighten-3'"
            small
            text
            v-bind="attrs"
            v-on="on"
            title="Settings"
          >
            <v-icon small>mdi-cog-outline</v-icon>
          </v-btn>
        </v-hover>
      </template>

      <v-list dense>
        <v-list-item href="/settings/equipment">
          <v-list-item-content>
            <v-list-item-title>Equipment list</v-list-item-title>
            <v-list-item-subtitle>Manage the list of equipment reported in logs</v-list-item-subtitle>
          </v-list-item-content>
          <v-list-item-action><v-icon small>mdi-view-list</v-icon></v-list-item-action>
        </v-list-item>
        <template v-if="false">
          <v-divider></v-divider>
          <v-list-item href="/settings">
            <v-list-item-content>
              <v-list-item-title>Local settings</v-list-item-title>
              <v-list-item-subtitle>Manage this vessel's configuration</v-list-item-subtitle>
            </v-list-item-content>
            <v-list-item-action><v-icon small>mdi-ferry</v-icon></v-list-item-action>
          </v-list-item>
        </template>
      </v-list>

    </v-menu>


    <v-breadcrumbs :items="path">
      <template v-slot:item="{ item }">
        <v-breadcrumbs-item :href="item.href" :disabled="item.disabled" v-if="item.organisations">
          <v-tooltip bottom>
            <template v-slot:activator="{ on, attrs }">
              <span v-bind="attrs" v-on="on">{{ item.text }}</span>
            </template>
            <div class="text-overline">Project permissions</div>
            <v-simple-table dense>
              <template v-slot:default>
                <thead>
                  <tr>
                    <th>Organisation</th><th>Read</th><th>Write</th><th>Edit</th>
                  </tr>
                </thead>
                <tbody>
                  <tr v-for="(operations, name) in item.organisations">
                    <td v-if="name == '*'"><v-chip small label color="primary">All</v-chip></td>
                    <td v-else><v-chip small label outlined>{{ name }}</v-chip></td>
                    <td>{{ operations.read ? "✔" : " " }}</td>
                    <td>{{ operations.write ? "✔" : " " }}</td>
                    <td>{{ operations.edit ? "✔" : " " }}</td>
                  </tr>
                </tbody>
              </template>
            </v-simple-table>
          </v-tooltip>
        </v-breadcrumbs-item>
        <v-breadcrumbs-item :href="item.href" :disabled="item.disabled" v-else>
          {{ item.text }}
        </v-breadcrumbs-item>
      </template>
    </v-breadcrumbs>

    <template v-if="$route.name != 'Login'">
      <v-btn text link to="/login" v-if="!user && !loading">Log in</v-btn>
      <template  v-else-if="user">

        <v-menu
          offset-y
        >
          <template v-slot:activator="{ on: menu, attrs }">
            <v-tooltip bottom>
              <template v-slot:activator="{ on: tooltip }">
              <v-avatar :color="user.colour || 'primary'" v-bind="attrs" v-on="{...tooltip, ...menu}">
                <span class="white--text">{{user.name.slice(0, 5)}}</span>
              </v-avatar>
              </template>
              <div class="text-overline">{{ user.name }}</div>
              <v-card flat class="my-1" v-if="user.description">
                <v-card-text class="pb-1" v-html="$root.markdown(user.description)">
                </v-card-text>
              </v-card>
              <v-simple-table dense>
                <template v-slot:default>
                  <thead>
                    <tr>
                      <th>Organisation</th><th>Read</th><th>Write</th><th>Edit</th>
                    </tr>
                  </thead>
                  <tbody>
                    <tr v-for="org in user.organisations">
                      <td v-if="org.name == '*'"><v-chip small label color="primary">All</v-chip></td>
                      <td v-else><v-chip small label outlined>{{ org.name }}</v-chip></td>
                      <td>{{ org.operations.read ? "✔" : " " }}</td>
                      <td>{{ org.operations.write ? "✔" : " " }}</td>
                      <td>{{ org.operations.edit ? "✔" : " " }}</td>
                    </tr>
                  </tbody>
                </template>
              </v-simple-table>
            </v-tooltip>
          </template>

          <v-list dense>
            <v-list-item link to="/login" v-if="user.autologin">
              <v-list-item-icon><v-icon small>mdi-login</v-icon></v-list-item-icon>
              <v-list-item-content>
                <v-list-item-title>Log in as a different user</v-list-item-title>
                <v-list-item-subtitle>Autologin from {{user.ip}}</v-list-item-subtitle>
              </v-list-item-content>
            </v-list-item>
            <v-list-item link to="/logout" v-else>
              <v-list-item-icon><v-icon small>mdi-logout</v-icon></v-list-item-icon>
              <v-list-item-content>
                <v-list-item-title>Log out</v-list-item-title>
              </v-list-item-content>
            </v-list-item>
            <v-divider></v-divider>
            <template v-if="canManageUsers">
            <v-list-item link to="/users">
              <v-list-item-icon><v-icon small>mdi-account-multiple</v-icon></v-list-item-icon>
              <v-list-item-content>
                <v-list-item-title>Manage users</v-list-item-title>
                <v-list-item-subtitle>Add, edit and remove users</v-list-item-subtitle>
              </v-list-item-content>
            </v-list-item>
            </template>
            <template v-else-if="user && !user.autologin">
            <v-list-item link :to="`/users/${user.id}`">
              <v-list-item-icon><v-icon small>mdi-account</v-icon></v-list-item-icon>
              <v-list-item-content>
                <v-list-item-title>User profile</v-list-item-title>
                <v-list-item-subtitle>Edit your user profile</v-list-item-subtitle>
              </v-list-item-content>
            </v-list-item>
            </template>
          </v-list>

        </v-menu>

      </template>
    </template>
    <template v-slot:extension v-if="appBarExtension">
      <div :is="appBarExtension"></div>
    </template>
  </v-app-bar>

</template>

<script>
import { mapActions, mapGetters } from 'vuex';

export default {
  name: 'DougalNavigation',
  data() {
    return {
      drawer: false,
      path: []
    };
  },

  computed: {

    appBarExtension () {
      return this.$route.matched
        .filter(i => i.meta?.appBarExtension)
        .map(i => i.meta.appBarExtension)
        .pop()?.component;
    },

    title () {
      return this.user.name + "\n" + [...this.user.organisations].map( ({name, operations}) => {
        if (name == "*") name = "All organisations";
        let str = name+": ";
        str += [ "read", "write", "edit" ].map( op => operations[op] ? op : null ).filter( op => op ).join(", ");
        return str;
      }).join("\n")
    },

    canManageUsers () {
      return this.user.organisations.accessToOperation("edit").length;
    },

    ...mapGetters(['user', 'loading'])
  },

  watch: {
    "$route" (newVal, oldVal) {
      if (newVal.matched != oldVal.matched) {
        this.breadcrumbs();
      }
    },

    "$store.state.project.projectId" () {
      this.breadcrumbs();
    }
  },

  methods: {

    breadcrumbs () {
      this.path = this.$route.matched
        .map(i => {
          return {
            breadcrumbs: i.meta && i.meta.breadcrumbs,
            ctx: i.instances.default
          }
        })
        .filter(i => i.breadcrumbs)
        .flat()
        .map(i => {

          return i.breadcrumbs.map( breadcrumb => {
            const o = {};
            for (const key of Object.keys(breadcrumb)) {
              o[key] = typeof breadcrumb[key] === 'function'
                ? i.ctx && breadcrumb[key](i.ctx)
                : breadcrumb[key];
            }
            return o;
          });
        })
        .flat();
    }
  },

  mounted () {
    this.breadcrumbs();
  }

};
</script>
