<template>
  <div>
    <field :label="schema.id.title" :info="schema.id.description" :schema="schema.id">
      <asset-picker
        v-model="valueCopy.id"
        :schema="schema.id"
        :variant-id="valueCopy.variantId"
        :required="!!schema.id.required"
        :readonly="!!schema.id.isReadOnly"
        :asset-type-filter-member="assetTypeFilterMember"
      ></asset-picker>
      <schema-validator :value="valueCopy.id" :schema="schema.id"></schema-validator>
    </field>

    <field label="Uitsnede" v-if="asset && isImage">
      <select v-model="valueCopy.variantId" class="form-control">
        <option selected :value="null">De originele afbeelding</option>
        <option v-for="variant in asset.variants" :value="variant.id" v-bind:key="variant.id">
          {{ variant.name }}
        </option>
      </select>
    </field>
  </div>
</template>

<script lang="ts">
import { Component, Prop, Vue, Watch } from 'vue-property-decorator';
import AssetApi from '../../api/asset-api';
import { isImage } from '../../api/asset-api-helpers';
import schemaValidator from '../../schema/schema-validator.vue';
import { ValueSync } from '../../tools/decorators';
import { Asset, AssetTypeFilter, SchemaImage } from '../../types/api';
import assetPicker from './asset-picker.vue';
import field from './field.vue';

interface ImagePickerValue {
  $type: string;
  id: string | null;
  variantId: string | null;
}

@Component({
  components: {
    assetPicker,
    schemaValidator,
    field
  }
})
export default class ImagePicker extends Vue {
  @ValueSync('value', { type: Object }) valueCopy!: ImagePickerValue;
  @Prop() readonly schema!: SchemaImage;

  asset: Asset | null = null;

  get isImage() {
    return isImage(this.asset);
  }

  get assetTypeFilterMember() {
    return this.valueCopy && this.valueCopy.$type == 'Q.Cms.Core.Domain.Atoms.Image, Q.Cms.Core.Domain'
      ? AssetTypeFilter.Image
      : AssetTypeFilter.All;
  }

  @Watch('valueCopy.id', { immediate: true })
  async handlerValueChange(assetId: string | null, oldAssetId: string | null) {
    // Only set variantId to null if an existing asset is removed or replaced
    if ((assetId && oldAssetId) || !assetId) {
      this.valueCopy.variantId = null;
    }

    this.asset = assetId ? await AssetApi.getAssetById(assetId) : null;
  }
}
</script>
