<template>
  <a :href="link" :target="target" v-on="on" :class="{[activeClass]: isActive}"><slot></slot></a>
</template>
<script lang="ts">
import { Vue, Component, Inject, Prop } from 'vue-property-decorator';
import { IPanel } from './PanelList.vue';
import {stackToHash} from "@itfin/components/src/components/panels/helpers";
import {getRootPanelList} from "@itfin/components/src/components/panels";

@Component({
  components: {
  },
  directives: {
  },
  filters: {
  }
})
export default class PanelLink extends Vue {
  @Inject({ default: null }) currentPanel;

  @Prop(Boolean) global: boolean;
  @Prop(String) panel: string;
  @Prop() payload: payload;
  @Prop() target: string;
  @Prop() list;
  @Prop({ type: String, default: 'active' }) activeClass: string;
  @Prop(Boolean) append: boolean;
  @Prop(Boolean) replace: boolean;

  get on() {
    const handlers = {};
    if (!this.target) {
      handlers.click = this.onClick;
    }
    return handlers;
  }

  get activeList() {
    return this.list ?? getRootPanelList();
  }

  get isActive() {
    if (!this.activeList) {
      return false;
    }
    let stack = this.activeList.getCurrentStack();
    return stack.find(s => s.type === this.panel);
  }

  get link() {
    let stack = this.activeList?.getCurrentStack() ?? [];
    if (!this.append) {
      stack = stack.splice(0, this.currentPanel?.index + 1);
    }
    if (this.replace) {
      stack = [];
    }
    const hash = stackToHash([
      ...stack,
      {
        type: this.panel,
        payload: this.payload || {}
      }
    ]);
    return hash;
  }

  onClick(e) {
    e.preventDefault();
    e.stopPropagation();
    const index = this.replace ? 0 : (this.append ? undefined : this.currentPanel?.index + 1);
    this.$emit('open', {
      panel: this.panel,
      payload: this.payload || {},
      index
    });
    if (!this.activeList) {
      return;
    }
    this.activeList.openPanel(this.panel, this.payload || {}, index);
  }
}
</script>
