<template>
  <div>
    <field label="Kopieer van" class="col-sm-12 form-group">
      <page-picker v-model="pageId" />
    </field>
    <field label="Kies de versie" class="col-sm-12 form-group">
      <select v-model="pageVersionId" :disabled="!pageVersions" class="form-control" v-if="pageVersions">
        <option :value="null" disabled>Kies de versie van de pagina</option>
        <template v-if="pageVersions">
          <option v-for="pageVersion in pageVersions" :key="pageVersion.id" :value="pageVersion.id">
            {{ pageVersion.name || '(Naamloze versie)' }}
            <template v-if="isLive(pageVersion)"> (live)</template>
          </option>
        </template>
      </select>
    </field>
  </div>
</template>

<style lang="scss" scoped>
ul {
  min-width: 200px;
  padding-left: 1.3em;
  margin: 0;
}
</style>

<script>
import pagePicker from '../shared/form/page-picker.vue';

import { getPublishedVersions } from './version-utils';
import PageApi from '../api/page-api';
import Field from '../shared/form/field.vue';

export default {
  data() {
    return {
      pageId: this.prefilledPageId,
      pageVersions: null,
      pageVersionId: null,
      livePageVersion: null
    };
  },
  props: {
    prefilledPageId: {
      default: null
    }
  },
  methods: {
    async setPage(pageId) {
      this.pageId = pageId;
      this.pageVersionId = null;
      this.pageVersions = null;

      const page = await PageApi.getPageById(pageId);
      if (page.versions && page.versions.length) {
        this.pageVersions = page.versions;

        const publishedVersion = getPublishedVersions(page.versions)[0];

        if (publishedVersion) {
          this.livePageVersion = publishedVersion;
          this.pageVersionId = publishedVersion.id;
        } else {
          this.pageVersionId = page.versions[0].id;
        }
      }
    },
    isLive(pageVersion) {
      return pageVersion == this.livePageVersion;
    }
  },
  watch: {
    pageId: {
      handler: function (pageId) {
        this.setPage(pageId);
      },
      immediate: true
    },
    pageVersionId(pageVersionId) {
      this.$emit('input', pageVersionId);
    }
  },
  components: {
    pagePicker,
    Field
  }
};
</script>
