<template>
  <li v-if="found">
    <span v-if="page.children && page.children.length" :class="['expander', expanded ? 'icon-minus' : 'icon-plus']" @click="expandCollapse()"></span>
    <p @click="choosePage" :class="{ 'not-enabled': !enabled, 'not-published': !isPublished(page.id) }">{{page.name}}
      <span v-if="!enabled">🚫</span>
    </p>
    <ul v-if="expanded">
      <page-picker-tree-item v-for="subPage in page.children" :page="subPage" :key="subPage.id" :search="search" :page-enabled-test="subpageEnabledTest" ref="children" v-on:page-chosen="bubbleEvent"></page-picker-tree-item>
    </ul>
  </li>
</template>

<style lang="scss" scoped>
ul, li {
  list-style: none;
  margin: 0;
  padding: 0;
  position: relative;
}
ul {
  padding-left: 1em;
}
p {
  margin: 0 2px;
  padding: 2px 3px;
  cursor: pointer;

  &.not-published {
    color: #bbb;
  }

  &.not-enabled {
    cursor: not-allowed;
  }

  &:not(.not-enabled):hover {
    background: #eee;
  }
}
.expander {
  cursor: pointer;
  position: absolute;
  right: 100%;
  top: 9px;
  font-size: 10px;
}
</style>

<script>
import { mapState } from 'vuex';

export default {
  name: 'page-picker-tree-item',
  props: {
    page: {
      type: Object
    },
    pageEnabledTest: {
      type: Function
    },
    search: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      expanded: window.localStorage[this.page.id + '-open'] != 'false'
    };
  },
  methods: {
    choosePage() {
      if (this.enabled) {
        this.bubbleEvent(this.page.id);
      }
    },
    bubbleEvent(pageId) {
      // page-picker-tree-item can be nested, so can't emit 'this.page.id', because that is the current page-picker-tree-item
      this.$emit('page-chosen', pageId);
    },
    expandCollapse() {
      this.expanded = !this.expanded;
      window.localStorage[this.page.id + '-open'] = '' + this.expanded;
    },
    isPublished(pageId) {
      return this.publishedPageIds.includes(pageId);
    }
  },
  computed: {
    ...mapState('pages', ['publishedPageIds']),
    pageEnabled() {
      if (this.page.disabled) {
        return false;
      }
      var pageEnabled = this.pageEnabledTest(this.page);
      if (!['enabled', 'disabled', 'subtree-disabled'].includes(pageEnabled)) {
        console.warn(`page-enabled-test must return 'enabled', 'disabled' or 'subtree-disabled', got ${pageEnabled}`);
      }
      return pageEnabled;
    },
    found() {
      return !this.search || this.page.name.toLowerCase().includes(this.search.toLowerCase())
        || (this.$refs.children && this.$refs.children.some(comp => comp.found));
    },
    enabled() {
      return this.pageEnabled == 'enabled';
    },
    subpageEnabledTest() {
      return this.pageEnabled == 'subtree-disabled'
        ? () => 'disabled'
        : this.pageEnabledTest;
    }
  }
};
</script>
