<template>
  <loader>
    <header class="page-header pt-4 pb-3">
      <h1>Details <span v-if="isReadOnly(asset)" class="crud-editor-readonly-title">[ Alleen lezen ]</span></h1>
      <div class="page-header-buttons">
        <references ref="refsDialog" v-if="asset && asset.id" :item-id="asset.sourceId" item-name="Asset"></references>
      </div>
    </header>
    <asset-detail :asset-prop="asset" v-model="uploadedAssetId" @deleteError="openReferencesErrorModal"></asset-detail>
  </loader>
</template>

<script>
import { mapState } from 'vuex';
import AssetApi from '../api/asset-api';
import assetDetail from './asset-detail.vue';
import loader from '../shared/loader.vue';
import references from '../shared/references.vue';
import { PermissionTypes } from '../stores/types/PermissionStoreModel';

export default {
  name: 'asset-detail-page',
  data() {
    return {
      asset: null,
      isLoadingAsset: true,
      uploadedAssetId: null
    };
  },
  async beforeRouteEnter(to, from, next) {
    if (to.params.id) {
      const asset = await AssetApi.getAssetById(to.params.id);

      return next((vm) => {
        (vm.asset = asset), (vm.isLoadingAsset = false);
      });
    } else {
      next((vm) => {
        vm.isLoadingAsset = false;
      });
    }
  },
  computed: {
    ...mapState('translations', ['isLoadingLanguageInfos']),
    isLoading() {
      return this.isLoadingAsset || this.isLoadingLanguageInfos;
    }
  },
  methods: {
    openReferencesErrorModal() {
      this.$refs.refsDialog.openErrorModal();
    },
    isReadOnly(asset) {
      return asset !== null && PermissionTypes[String(asset.userEntityPermission)] === PermissionTypes.Read;
    }
  },
  watch: {
    uploadedAssetId() {
      this.$router.push({ name: 'asset-overview' });
    }
  },
  components: {
    assetDetail,
    loader,
    references
  }
};
</script>
