<template v-if="version">
  <loader>
    <header class="meta card-body">
      <section class="form-group row">
        <div class="col-lg-12 version-actions">
          <button class="btn btn-success" @click="publish" :disabled="!permissions.canUpdate || changed || hasRecurringSchedules" v-if="version != state.live && publish">
            <span class="icon-rocket"></span> Live zetten
          </button>

          <button class="btn btn-warning" @click="depublish" :disabled="!permissions.canDepublish || hasRecurringSchedules" v-if="version == state.live && depublish">
            <span class="icon-switch"></span> Depubliceren
          </button>

          <button type="button" class="btn btn-primary preview-button ml-2" :class="stateClass" @click="openPreview" v-if="previewUrl"><span class="icon-eye"></span> Preview</button>

          <div class="right">
            <references ref="refsDialog" v-if="!isNew" :item-id="version.pageId" :item-name="version.page.name"></references>

          <button class="btn btn-danger mr-1" @click="cancel" :disabled="!changed" v-if="cancel">
              <span class="icon-undo"></span> Herstellen
            </button>
            <submit :action="save" v-if="save" :disabled="!permissions.canUpdate">
              <span class="icon-floppy-disk"></span> Wijzigingen opslaan
            </submit>
          </div>
        </div>
      </section>

      <section class="form-group row">
        <div class="col-lg-6 col-sm-12 version-header-block">
          <div>
            <schema-field v-model="version.name" :schema="versionSchemaProperties.name"></schema-field>
            <field label="Schedule start">
              <datetime-picker v-model="version.publishDate" :max="version.depublishDate" :readonly="hasRecurringSchedules"></datetime-picker>
            </field>

            <field label="Schedule stop">
              <datetime-picker v-model="version.depublishDate" :min="version.publishDate" :readonly="hasRecurringSchedules"></datetime-picker>
              <validator :test="!version.publishDate || !version.depublishDate || version.publishDate < version.depublishDate">
                Schedule start ligt na schedule stop
              </validator>
            </field>

            <div v-show="hasRecurringSchedules" class="footnote offset-sm-4 col-sm-8">
              Bij terugkerende schedules worden de start/stop velden automatisch gevuld op basis van de ingestelde schedules.
            </div>
          </div>

          <field label="Terugkerende schedule(s)" v-if="!isNew">
            <recurring-schedule-input :version="version" :recurrent-schedules.sync="recurringSchedules" :permissions="permissions"></recurring-schedule-input>
          </field>

          <schema-field v-model="version.canonical" :schema="versionSchemaProperties.canonical"></schema-field>
        </div>

        <div class="col-lg-6 col-sm-12 version-header-block">
          <schema-field v-model="version.metaTitle" :schema="versionSchemaProperties.metaTitle"></schema-field>
          <schema-field v-model="version.showPostFix" :schema="versionSchemaProperties.showPostFix"></schema-field>
          <schema-field v-model="version.metaDescription" :schema="versionSchemaProperties.metaDescription"></schema-field>
          <schema-field v-model="version.metaIndex" :schema="versionSchemaProperties.metaIndex"></schema-field>
          <schema-field v-model="version.metaFollow" :schema="versionSchemaProperties.metaFollow"></schema-field>
        </div>
      </section>
    </header>

    <editor :item="version" :schema="schema"></editor>
    <validator :test="changed"></validator>
  </loader>
</template>

<style lang="scss" scoped>
  .meta {
    background: linear-gradient(to bottom, #fff 60%, rgba(255,255,255, 0) 100%);
    border-left: 1px solid #ddd;
    border-right: 1px solid #ddd;
  }

  .version-actions {
    display: flex;

    .right {
      margin-left: auto;
    }
  }

  .footnote {
    color: #55595c;
    font-size: 14px;
    margin-bottom: 1.3rem;
  }

  .references {
    display: inline-block;
  }
</style>

<script>
import { pageStore } from '../tools/page-store.js';
import editor from '../shared/editor.vue';
import loader from '../shared/loader.vue';
import * as formElements from '../shared/form/all.js';
import references from '../shared/references.vue';
import recurringScheduleInput from '../shared/form/recurring-schedule-input.vue';

export default {
  props: ['version', 'state', 'publish', 'depublish', 'save', 'cancel', 'permissions'],
  data() {
    return {
      changed: false,
      preview: false,
      versionCounter: 0,
      previewWindow: null,
      recurringSchedules: []
    }
  },
  watch: {
    version: {
      handler(newValue, oldValue) {
        // the whole version can change as well, only set 'changed' prop when editing on the same version
        if (newValue.id == oldValue.id) {
          this.changed = true;
        } else {
          this.resetChanged();
        }
      },
      deep: true
    }
  },
  computed: {
    isNew() {
      return !this.version.id;
    },
    previewUrl() {
      // Updating the versionCounter is will trigger a refresh of the preview iframes
      return pageStore.previewUrl(this.version, this.versionCounter);
    },
    stateClass(){
      return this.version == this.state.live ? 'btn-success' : this.state.published ? 'btn-warning' : 'disabled';
    },
    versionSchemaProperties: () => pageStore.schema.properties,
    types: () => pageStore.types,
    isLoading() {
      return pageStore.isLoading || !this.schema;
    },
    schema() {
      return this.types[this.version.$type];
    },
    hasRecurringSchedules() {
      return this.recurringSchedules.length > 0;
    }
  },
  methods: {
    resetChanged() {
      // There might be pending changes to this.version, wait those out.
      this.$nextTick(() => {
        this.changed = false;
        this.versionCounter++;

        // update preview window with the new version
        try {
          this.previewWindow.location = this.previewUrl;
        } catch(e) {
          // errors can safely be ignored
        }
      });
    },
    openPreview() {
      this.previewWindow = window.open(this.previewUrl);
    },
    openReferencesErrorModal() {
      this.$refs.refsDialog.openErrorModal();
    }
  },
  components: {
    editor,
    loader,
    recurringScheduleInput,
    references,
    ...formElements
  }
}
</script>
