<template>
  <li class="list-group-item" v-show="showPage(page)">

    <span v-if="hasChildren" :class="['expander', expanded ? 'icon-minus' : 'icon-plus']" @click="expandCollapse()"></span>
    <router-link :to="{name: 'page-editor', params: {id: page.id}, activeClass: 'active'}" class="page-tree-item" :class="{'not-published': !page.isPublished && !isLoadingPublishedState, 'loading': isLoadingPublishedState }">
      {{page.name}}
    </router-link>
    <router-link tag="button" v-if="canCreateChildren" class="btn btn-link page-tree-item page-create" :to="{name: 'page-create-in', params: { parentId: page.id }, activeClass: 'active'}">
      <span class="icon-file-empty"></span> nieuwe subpagina
    </router-link>
    <ul class="list-group" v-if="hasChildren && expanded">
      <page-tree-item v-for="subPage in page.children" :page="subPage" :key="subPage.id" :show-page="showPage" :is-loading-published-state="isLoadingPublishedState"></page-tree-item>
    </ul>
  </li>
</template>

<style lang="scss" scoped>
  $expandIconSize: 10px;

  .list-group {
    border: none;
    padding-left: $expandIconSize * 2;
    margin-left: 0;

    .list-group-item {
      border: none;
      padding-bottom: 5px;
      padding-top: 5px;
      padding-right: 0;
      margin-bottom: 0; // Removes weird margin-bottom -1 from bootstrap.
      margin-left: 0;
      padding-left: 0;
    }
  }

  .page-tree-item {
    margin-left: $expandIconSize * 1.5;
    padding: 3px;
    border-radius: 3px 5px;

    & ~ .page-create {
      display: none;
      margin-left: $expandIconSize * 3.5;
      font-size: 90%;
      &.active {
        display: block;
      }
    }

    &.loading {
      animation: loading 0.8s infinite ease-in-out;
    }

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

    &.active {
      background: #ccc;

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

      & ~ .page-create {
        display: block;
      }
    }
  }
  a.page-tree-item {
    color: inherit;
  }

  .expander {
    cursor: pointer;
    font-size: $expandIconSize;

    + .page-tree-item {
      margin-left: 0;
    }
  }

  @keyframes loading {
    0% {
      color: #bbb;
    }

    50% {
      color: inherit;
    }

    100% {
      color: #bbb;
    }
  }
</style>

<script>
  import { permissionStore } from '../tools/permission-store.js';

  export default {
    name: 'page-tree-item',
    props: ['page', 'showPage', 'isLoadingPublishedState'],
    data() {
      return {
        expanded: window.localStorage[this.page.id + '-open'] != 'false'
      };
    },
    methods: {
      expandCollapse() {
        this.expanded = !this.expanded;
        window.localStorage[this.page.id + '-open'] = '' + this.expanded;
      }
    },
    computed: {
      hasChildren() {
        return this.page.children && this.page.children.length;
      },
      canCreateChildren() {
        return this.page.allowNew && permissionStore.canCreate(this.page.itemName);
      }
    }
  };
</script>
