<template>
  <div class="page-picker">
    <popup v-if="customInput" ref="popup" overflow>
      <ul>
        <page-picker-tree-item v-for="page in pageTree" :page="page" :key="page.id" :page-enabled-test="pageEnabledTest" v-on:page-chosen="setPage"></page-picker-tree-item>
      </ul>
    </popup>

    <picker-helper v-else v-model="search" ref="picker" :readonly="readonly">
      <template slot="value">
        <picker-value :ondelete="ondelete" v-if="canDelete && path">{{path}}</picker-value>
        <picker-value v-if="!canDelete">{{path}}</picker-value>
      </template>
      <ul slot="options">
        <page-picker-tree-item v-for="page in pageTree" :page="page" :key="page.id" :search="search" :page-enabled-test="pageEnabledTest" v-on:page-chosen="setPage"></page-picker-tree-item>
      </ul>
    </picker-helper>
  </div>
</template>

<style lang="scss" scoped>
ul {
  min-width: 200px;
  padding-left: 1.3em;
  margin: 0;
}
</style>

<script>
import { pageStore } from '../../tools/page-store.js';
import { ValueSyncMixin } from '../value-sync-mixin.js';
import pagePickerTreeItem from './page-picker-tree-item.vue';
import pickerHelper from '../picker-helper.vue';
import pickerValue from '../picker-value.vue';
import popup from '../popup.vue';

export default {
  mixins: [ValueSyncMixin],
  props: {
    value: {
      required: true,
      validator: value => value === null || typeof value === 'string',
      demoValue: null
    },
    readonly: {
      type: Boolean,
      default: false
    },
    required: {
      type: Boolean,
      default: false
    },
    customInput: {
    },
    pageEnabledTest: {
      type: Function,
      default: () => 'enabled'
    }
  },
  data() {
    return {
      search: ''
    }
  },
  computed: {
    pages: () => pageStore.pages,
    pageTree: () => pageStore.pageTree,
    path() {
      const page = this.pages.find(page => page.id == this.valueCopy);
      return page ? page.path : null;
    },
    canDelete() {
      return !this.required && !this.readonly;
    }
  },
  methods: {
    ondelete() {
      this.valueCopy = null
    },
    showPopup() {
      this.customInput ? this.$refs.popup.show(this.customInput) : this.$refs.picker.showPopup();
    },
    hidePopup() {
      this.customInput ? this.$refs.popup.hide() : this.$refs.picker.hidePopup();
    },
    setPage(pageId) {
      this.valueCopy = pageId;

      // Come after the next focus event
      setTimeout(() => {
        this.hidePopup();
      }, 0);
    }
  },
  components: {
    pagePickerTreeItem,
    pickerHelper,
    pickerValue,
    popup
  }
}
</script>
