<template>
  <div>
    <field :label="schema.id.title" :info="schema.id.description">
      <asset-picker :variant-id="this.valueCopy.variantId" v-model="valueCopy.id" :required="!!schema.id.required" :readonly="!!schema.id.isReadOnly"/>
      <schema-validator :value="valueCopy.id" :schema="schema.id"/>
    </field>
    <field v-if="valueCopy && valueCopy.id">
      <router-link class="btn btn-secondary" :to="{name: 'asset-edit', params: { id: valueCopy.id }}" >Bekijk in asset manager</router-link>
    </field>
    <field label="Uitsnede" v-if="asset">
      <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" :key="variant.id">
          {{variant.name}}
        </option>
      </select>
    </field>
  </div>
</template>

<script>
import schemaValidator from '../../schema/schema-validator.vue';
import assetPicker from './asset-picker.vue';
import { ValueSyncMixin } from '../value-sync-mixin.js';
import field from './field.vue';
import AssetApi from '../../api/asset-api';

export default {
  name: 'image-picker',
  mixins: [ValueSyncMixin],
  props: {
    value: {
      required: true,
      docs: `Het <code>Image</code> object.`,
      demoValue: null
    },
    schema: {
      type: Object,
      required: true,
      docs: `Het <code>schema</code> dat bij het image object hoort.`,
      demoValue: () => ({
        $type: 'Q42.Cms.Domain.Atoms.Image',
        format: 'image-picker'
      })
    }
  },
  data() {
    return {
      asset: undefined
    }
  },
  watch: {
    'value.id': [
      {
        immediate: true,
        async handler(assetId) {
          if (!assetId) {
            return;
          }
          this.asset = await AssetApi.getAssetById(assetId);
        }
      },
      function () {
        this.valueCopy.variantId = null;
      }
    ]
  },
  components: {
    assetPicker,
    field,
    schemaValidator
  }
}
</script>
