<template>
  <transition
    name="alternate"
    mode="in-out"
  >
    <div class="alternate">
      <div
        class="image-item"
      >
        <img
          :ref="`custom-image${ name ? '' : '-temporal' }`"
          :src="imageSrc"
        >
        <div class="actions">
          <ui-icon-button
            button-type="button"
            icon="delete"
            type="secondary"
            @click="removeAlternate"
          />
          <copy-to-clipboard
            :text="linkSrc"
            :disabled="!selectedName"
          />
        </div>
      </div>
      <div class="custom-item-details">
        <ui-select
          :disabled="!!selectedName"
          :value="selectedNameUpperCase"
          :class="{ selected: !selectedName}"
          floating-label
          disable-filter
          label="Rendition Name*"
          help="* Required field"
          :options="formattedRenditionNames"
          @select="selectName"
        >
          <template
            slot="option"
            slot-scope="{option = {}}"
          >
            <div
              class="option-item"
              :class="{disabled: option.class}"
            >
              <span class="option-text">
                {{ option.label }}
              </span>
            </div>
          </template>
        </ui-select>
        <ui-alert
          v-show="showAlert"
          type="error"
          :dismissible="false"
        >
          This action replaces the rendition.
        </ui-alert>
      </div>
    </div>
  </transition>
</template>
<script>

import CopyToClipboard from 'Components/tools/CopyToClipboard.vue';
import { ALTERNATES } from 'Config/constants';
import { getCustomPath, getImageSrc } from 'Helpers/asset';

const {
    UiAlert,
    UiIconButton,
    UiSelect
  } = window.kiln.utils.components,
  HIDE_ALERT_TIMEOUT = 5000;

export default {
  components: {
    CopyToClipboard,
    UiAlert,
    UiIconButton,
    UiSelect
  },
  props: {
    keyName: {
      type: String,
      default: ''
    },
    name: {
      type: String,
      default: ''
    },
    path: {
      type: String,
      default: ''
    },
    parentPath: {
      type: String,
      default: ''
    },
    imageUploaded: {
      type: Boolean,
      default: false
    },
    renditionNames: {
      type: Object,
      default: () => ({})
    },
    formattedRenditionNames: {
      type: Array,
      default: () => [{}]
    },
    validate: {
      type: Function,
      default: () => ({})
    }
  },
  data() {
    return {
      selectedName: '',
      selectedNameUpperCase: '',
      showAlert: false
    };
  },
  computed: {
    customPath() {
      return getCustomPath(this.selectedName, this.parentPath);
    },
    imageSrc() {
      return this.path || this.linkSrc;
    },
    linkSrc() {
      return getImageSrc(this.customPath);
    },
    nameIsSilo() {
      return this.selectedName === ALTERNATES.SILO.ref;
    }
  },
  watch: {
    imageUploaded(finishedUploading) {
      if (finishedUploading) {
        this.showAlert = false;
      }
    },
    keyName() {
      this.selectedName = this.keyName;
    },
    name() {
      this.selectedNameUpperCase = this.name;
    }
  },
  mounted() {
    this.selectedName = this.keyName;
    this.selectedNameUpperCase = this.name;
  },
  methods: {
    /**
     * Handles the click on remove button
     */
    removeAlternate() {
      this.$emit('removeAlternate', this.customPath, this.keyName);
    },
    /**
     * Saves the new alternate
     */
    saveRendition() {
      this.$emit('saveAlternate', this.selectedName);
    },
    /**
     * Handles the selection of a named rendition
     * @param {Event} e
     * @returns {undefined}
     */
    selectName(e) {
      if (e.class === 'disabled') {
        return;
      }

      this.selectedName = e.value;
      this.selectedNameUpperCase = e.label;
      this.$emit('replaceRendition', this.selectedName);

      // if selected name and is silo, save right away
      if (this.selectedName && this.nameIsSilo) {
        return this.saveRendition();
      }

      // validation is needed for other renditions
      const {
        naturalHeight,
        naturalWidth
      } = this.$refs['custom-image-temporal'];

      if (this.validate(this.selectedName, naturalHeight, naturalWidth)) {
        this.showAlert = true;

        // alert to last 5 seconds and then save is executed
        setTimeout(() => {
          this.saveRendition();
        }, HIDE_ALERT_TIMEOUT);

        return;
      }

      // if we got to this point is because validation failed
      this.selectedName = '';
      this.selectedNameUpperCase = '';

      this.$emit('validationFailed');
    }
  }
};
</script>
<style lang="scss" scoped>
  @import 'Styles/colors.scss';
  @import 'Styles/helpers.scss';

  .alternate {
    margin: 0 20px 20px 10px;
  }

  .image-item {
    display: inline-block;

    .actions {
      text-align: right;
    }

    img {
      border: solid 1px $border-color;
      display: block;
      max-height: 300px;
      max-width: 300px;
    }
  }

  .custom-item-details {
    display: inline-block;
    margin-left: 40px;
    vertical-align: top;
    width: 320px;

     /deep/ .ui-select {
       @extend .select-input-style;

       margin-bottom: 16px;

      .option-item {
        width: 100%;

        &.disabled {
          color: $disable-color--brighter;
          cursor: not-allowed;
        }
      }

      &.is-disabled {
        .ui-select__display,
        .ui-select__dropdown-button {
          color: $border-color-darker;
        }
      }

      &.selected:not(.is-disabled):not(.is-active) {

        .ui-select__label-text,
        .ui-select__dropdown-button {
            color: $orange-red;
        }

        .ui-select__display {
            border-bottom-color: $orange-red;
        }
      }
    }
  }

  .alternate-enter-active {
    animation: scroll-down .4s;
  }

  .alternate-leave-active {
    animation: scroll-down .4s reverse;
  }

  @keyframes scroll-down {
    0% {
      transform: scale(0);
      opacity: 0;
    }
    25% {
      transform: scale(0.25);
      opacity: 0.25;
    }
    50% {
      transform: scale(0.5);
      opacity: 0.5;
    }
    75% {
      transform: scale(0.75);
      opacity: 0.75;
    }
    100% {
      transform: scale(1);
      opacity: 1;
    }
  }

</style>
