<template>
  <div>
    <header class="page-header pt-4 pb-3">
      <h1>Overzicht</h1>

      <div class="page-header-buttons">
        <router-link class="btn btn-secondary mr-2" to="/cms-tags" v-if="permissions.canCreate">Tags beheren</router-link>
        <router-link class="btn btn-primary" :to="{ name: 'asset-create' }" v-if="permissions.canCreate"
          ><span class="icon-plus"></span> Toevoegen</router-link
        >
        <span class="btn btn-primary disabled" v-else><span class="icon-plus"></span> Toevoegen</span>
      </div>
    </header>

    <asset-overview v-model="assetIdToNavigateTo"></asset-overview>
  </div>
</template>

<script lang="ts">
import { Component, Vue, Watch } from 'vue-property-decorator';
import { namespace } from 'vuex-class';
import { AssetSearchResult } from '../api/asset-api';
import { AssetSearchState } from '../stores/modules/asset-store';
import assetOverview from './asset-overview.vue';

const AssetStore = namespace('assets');
const PermissionsStore = namespace('permissions');

@Component({
  components: {
    assetOverview
  }
})
export default class AssetOverviewPage extends Vue {
  assetIdToNavigateTo: string | null = null;

  @AssetStore.State('searchState') readonly assetSearchState!: AssetSearchState;
  @AssetStore.Mutation('searchState') readonly setAssetSearchState!: (searchState: AssetSearchResult) => void;
  @AssetStore.Action('fetchItems') readonly fetchAssets!: () => Promise<void>;
  @PermissionsStore.Getter('getPermissions') readonly getPermissions!: Function;

  @Watch('assetIdToNavigateTo')
  onChangeSelecedAsset(assetId: string | null) {
    if (assetId) {
      this.$router.push({ name: 'asset-edit', params: { id: assetId } });
    }
  }

  @Watch('assetSearchState', { deep: true })
  async onAssetSearchStateChange() {
    this.updateQueryParams();
  }

  get permissions() {
    return this.getPermissions('CmsAsset');
  }

  mounted() {
    try {
      const searchState = JSON.parse(this.$route.query.state + '');
      this.setAssetSearchState(searchState);
    } catch {
      this.fetchAssets;
    }
  }

  updateQueryParams() {
    const routerConfig = {
      query: {
        state: JSON.stringify(this.assetSearchState)
      }
    };

    this.$router.replace(routerConfig);
  }
}
</script>
