<template>
  <modal ref="modal" large>
    <header class="modal-header">
      <h3 class="modal-title">Kies bestand</h3>
      <button type="button" class="close" @click.prevent="closeModal" aria-label="Close">
        <span aria-hidden="true">&times;</span>
      </button>
    </header>
    <div class="modal-body">
      <button class="btn btn-primary" @click.prevent="createAsset" v-if="mode === modes.Overview">Upload bestand</button>
      <p class="mb-0" v-if="mode === modes.Overview">of selecteer uit de lijst</p>
      <asset-overview v-if="mode === modes.Overview" v-model="asset" :type="type" modal />
      <asset-detail v-if="mode === modes.Create" ref="asset-detail" @cancel="closeModal" v-model="asset" :default-image-crops="[]" />
    </div>
  </modal>
</template>

<script lang="ts">
import { Component, Prop, Vue, Watch, Ref } from 'vue-property-decorator';

import Modal from '../../shared/modal.vue';
import AssetOverview from '../../assets/asset-overview.vue';
import AssetDetail from '../../assets/asset-detail.vue';
import { Asset, AssetTypeFilter } from '../../types/api';

export enum AssetModalMode {
  Overview = 'overview',
  Create = 'create'
}

@Component({
  components: {
    Modal,
    AssetDetail,
    AssetOverview
  }
})
export default class AssetModal extends Vue {
  @Prop(Number) readonly type!: AssetTypeFilter;
  @Prop(Object) readonly value!: Asset;

  @Ref() readonly modal!: any;
  @Ref() readonly assetDetail!: AssetDetail;

  mode: AssetModalMode = AssetModalMode.Overview;
  modes = AssetModalMode;
  asset: Asset | null = null;

  createAsset() {
    this.mode = AssetModalMode.Create;
  }

  openModal(mode: AssetModalMode) {
    this.mode = mode;
    this.modal.show();
  }

  closeModal() {
    this.modal.hide();
  }

  onFileDrop(file: File) {
    this.assetDetail.selectFile(file);
  }

  @Watch('asset')
  async onAssetChange(newAsset: Asset) {
    if (newAsset) {
      this.$emit('input', newAsset);
    } else {
      this.$emit('input', null);
    }
  }
}
</script>
