<template>
  <div v-if="showModal">
    <ui-modal
      ref="metadata-modal"
      dismiss-on="backdrop close-button"
      @hide="closeAndClear"
    >
      <template
        slot="header"
      >
        <div class="modal-header-title">
          Shared Metadata
        </div>
        <div class="shared-meta-count">
          Editing {{ selectedIds.length }} images
        </div>
      </template>
      <form>
        <ui-select
          v-model="assetType"
          class="form-element"
          floating-label
          disable-filter
          label="Asset Type"
          :options="assetTypes"
        />
        <ui-textbox
          v-model.trim="credit"
          class="form-element"
          floating-label
          label="Credit"
        />
        <ui-textbox
          v-model.trim="creditUrl"
          class="form-element"
          floating-label
          label="Credit URL"
        />
        <collection-slug
          edit-mode
          modal-mode
          :value="collectionSlug"
          @fieldChange="saveField"
        />
        <tags
          :provided-tags="providedTags"
          :selected-tags="selectedTags"
          placeholder="Select from list"
          @selectTags="saveTags"
        />
        <keywords
          label="Keywords"
          :items="metaKeywords"
          @saveKeywords="saveKeywords"
        />
      </form>
      <template slot="footer">
        <transition
          name="fade"
          mode="out-in"
        >
          <ui-button
            button-type="button"
            class="save"
            color="accent"
            :disabled="saveDisabled"
            type="secondary"
            @click="save"
          >
            Save
          </ui-button>
        </transition>
        <ui-button
          button-type="button"
          class="save-and-edit"
          color="accent"
          :disabled="saveDisabled"
          icon="open_in_new"
          @click="saveAndEdit"
        >
          Save and edit images
        </ui-button>
      </template>
    </ui-modal>
  </div>
</template>
<script>

import { updateMultiple } from 'Api';
import { hasStatusError } from 'Helpers/api';
import CollectionSlug from 'Components/metadata/CollectionSlug.vue';
import Tags from 'Components/metadata/Tags.vue';
import Keywords from 'Components/metadata/Keywords.vue';
import { ALPHANUMERIC_NO_UNDERSCORE_RE } from 'Config/constants';

const {
    UiButton,
    UiModal,
    UiSelect,
    UiTextbox
  } = window.kiln.utils.components,
  metadataFields = {
    assetType: 'assetType',
    credit: 'credit',
    creditUrl: 'creditUrl',
    collectionSlug: 'collectionSlug',
    metaKeywords: 'keywords',
    selectedTags: 'tags'
  };

export default {
  components: {
    CollectionSlug,
    UiButton,
    UiModal,
    UiSelect,
    UiTextbox,
    Keywords,
    Tags
  },
  props: {
    assetTypes: {
      type: Array,
      default: () => []
    },
    providedTags: {
      type: Object,
      default: () => ({})
    },
    selectedIds: {
      type: Array,
      default: () => []
    },
    metadataModalState: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      assetType: '',
      credit: '',
      creditUrl: '',
      collectionSlug: '',
      metaKeywords: [],
      selectedTags: [],
      editMode: false,
      showModal: false
    };
  },
  computed: {
    saveDisabled() {
      return !this.assetType && !this.credit && !this.creditUrl && !this.collectionSlug
        && !this.metaKeywords.length && !this.selectedTags.length;
    }
  },
  watch: {
    metadataModalState(openModal) {
      if (openModal) {
        return this.openModal();
      }

      this.closeModal();
    }
  },
  methods: {
    openModal() {
      this.showModal = true;

      // wait for next tick before opening modal
      this.$nextTick(() => {
        this.$refs['metadata-modal'].open();
      });
    },
    closeModal() {
      this.$refs['metadata-modal'].close();

      // wait for next tick before removing the element
      this.$nextTick(() => {
        this.showModal = false;
      });
    },
    /**
     * Saves general metadata fields into data
     * @param {string} metaField
     * @param {string} metaValue
     */
    saveField(metaField, metaValue) {
      this[metaField] = metaValue;
    },
    /**
     * Closes and clears modal
     */
    closeAndClear() {
      this.$emit('closeMetadataModal');
      this.clearModal();
    },
    /**
     * Clears metadata fields in modal
     */
    clearModal() {
      this.assetType = '';
      this.credit = '';
      this.creditUrl = '';
      this.collectionSlug = '';
      this.metaKeywords = [];
      this.selectedTags = [];
      this.editMode = false;
    },
    /**
     * Sets edit mode and saves metadata
     */
    saveAndEdit() {
      this.editMode = true;
      this.save();
    },
    /**
     * Saves shared metadata in all assets selected
     */
    save() {
      const metadata = Object.entries(metadataFields).reduce((accum, [name, field]) => {
        if (this[name].length) {
          return {
            ...accum,
            [field]: this[name]
          };
        }
        return accum;
      }, {});

      // eslint-disable-next-line one-var
      const sharedMetadata = {
        asset: {
          metadata
        }
      };

      updateMultiple(this.selectedIds, sharedMetadata)
        .then((resp) => {
          resp.forEach((data) => {
            if (hasStatusError(data)) {
              this.$emit('alert', { text: `${data.error}: ${data.message}` });
            }
          });
        })
        .then(() => {
          this.editMode
            ? this.$emit('editSelection')
            : this.$emit('closeAndRefresh');

          this.clearModal();
        })
        .catch(console.error);
    },
    /**
     * Saves tags received into data
     * @param {string[]} tags
     */
    saveTags(tags = []) {
      this.selectedTags = tags;
    },
    /**
     * Saves keywords received into data
     * @param {string[]} keywords
     */
    saveKeywords(keywords = []) {
      this.metaKeywords = keywords;
    },
    /**
     * Handles text input restrictions
     * @param {Object} event Input event
     */
    handleTextRestrictions(event) {
      if (!event.key.match(ALPHANUMERIC_NO_UNDERSCORE_RE)) {
        event.preventDefault();
      }
    }
  }
};
</script>
<style lang="scss" scoped>
  @import 'Styles/colors.scss';
  @import 'Styles/fonts.scss';
  @import 'Styles/helpers.scss';

  .modal-header-title {
    color: $border-color-darker;
    position: absolute;
    top: 24px;
  }

  /deep/ .ui-select {
    margin-bottom: 0;
  }

  /deep/ .ui-modal__container {
    width: 43em;
    overflow: visible;

    .ui-modal__header {
      box-shadow: none;
      background-color: $white;
      height: 6rem;
      position: relative;

      .shared-meta-count {
        font-size: $standard-font-size;
        position: absolute;
        text-transform: uppercase;
        top: 61px;
      }

      .ui-modal__close-button {
        position: absolute;
        right: 20px;
        top: 20px;
      }
    }

    .ui-modal__body {
      padding: 0 1.5rem;
      overflow-y: visible;

      form {
        align-items: flex-start;
        display: flex;
        flex: 26em 0;
        flex-flow: column;
        color: $font-primary;

        .form-element {
          padding: 8px 0;
          width: 100%;
        }

        .is-floating {
          font-size: $small-font-size;
          height: 20px;
        }
      }
    }

    .ui-modal__footer {
      height: 5.25rem;
      margin-top: 1rem;

      .save {
        border: 1px solid $overlay-color;
      }
    }
  }
</style>
