<script lang="ts">
import { Vue, Component, Prop, Ref } from 'vue-property-decorator';
import { Page } from '../types/api';
import { namespace } from 'vuex-class';

import RouteUtils, { createRoute, ROUTES } from '../tools/route-utils';

const PageStore = namespace('pages');

@Component({
  name: 'NestedPageTableItem'
})
export default class NestedPageTableItem extends Vue {
  @Prop({ type: Object, required: true }) readonly page!: Page;
  @Prop({ type: Boolean, default: () => true }) readonly opened!: boolean;
  @Prop({ type: Number, default: () => 0 }) readonly parents!: number;
  @Prop({ type: Function, required: true }) readonly showPage!: Function;
  @Prop({ type: Boolean, default: false }) readonly defaultChildrenOpened!: boolean;

  @Ref() readonly nestedPageTableItem!: NestedPageTableItem[] | NestedPageTableItem;

  @PageStore.Getter('isFolder') readonly isFolder!: (page: Page) => boolean;
  @PageStore.Getter('isVirtualPage') readonly isVirtualPage!: (page: Page) => boolean;

  childrenOpened = false;

  mounted() {
    this.childrenOpened = this.defaultChildrenOpened;
  }

  toggleChildren() {
    this.childrenOpened = !this.childrenOpened;
    this.$emit('toggle');
  }

  async toggleSelfAndChildren(value: boolean) {
    this.childrenOpened = value;

    // Make sure to wait for its children to render recursively first
    await this.$nextTick();

    if (!this.nestedPageTableItem) {
      return;
    }

    Array.isArray(this.nestedPageTableItem)
      ? this.nestedPageTableItem.forEach(item => item.toggleSelfAndChildren(value))
      : await this.nestedPageTableItem.toggleSelfAndChildren(value);
  }

  async openPage() {
    await RouteUtils.push(createRoute(ROUTES.PAGE_EDITOR, { id: this.page.id }))
  }

  get pageEditorRoute() {
    return ROUTES.PAGE_EDITOR;
  }

  get toggleStyling() {
    return {
      width: 24 * this.parents + 8 + 24 + 'px'
    };
  }

  get rowStyling() {
    return { backgroundColor: `rgba(0,0,0,${ 0.05 * this.parents })` }
  }

  get hasChildren() {
    return this.page.children.length > 0;
  }
}
</script>
