<template>
  <v-layout row>
    <div class="field-name">
      <b>Tags</b>
    </div>
    <div class="field-value">
      <v-autocomplete
        v-if="hasPermission && isEditable"
        ref="edit"
        :value="dirtyValue"
        :items="items"
        :loading="isLoading || loading"
        :search-input.sync="tagQuery"
        class="tag-editable-field"
        hint="Add existing or new keywords which are helpful when searching"
        prepend-icon="check"
        chips
        deletable-chips
        hide-selected
        hide-no-data
        no-filter
        return-object
        item-text="name"
        item-value="name"
        multiple
        @input="onSelect"
        @click:prepend="save"
        @keyup.enter="makeFieldNotEditable"
        @keyup.esc="cancelEdition">

        <template
          slot="selection"
          slot-scope="{ item, selected }">
          <v-chip
            :selected="selected"
            class="chip--select-multi"
            close
            @input="remove(item)">
            {{ item.name | truncate }}
          </v-chip>
        </template>
        <template
          slot="item"
          slot-scope="{ item, tile }">
          <v-list-tile-content>
            <v-list-tile-title v-text="item.name"/>
          </v-list-tile-content>
        </template>
      </v-autocomplete>

      <v-input
        v-else
        :class="['non-base-editable-field', 'tag-chips', !hasPermission && 'prevent-editing']"
        prepend-icon="edit"
        @click:prepend="hasPermission && makeFieldEditable">
        <div v-if="value && value.length" class="text-xs-center">
          <v-chip
            v-for="(tag, index) in value"
            :key="index">
            {{ tag.name }}
          </v-chip>
        </div>
        <span v-else>-</span>
      </v-input>

    </div>
  </v-layout>
</template>

<script>
import TagSearchInput from '../tags/TagSearchInput'
import { fetchListRecords } from '../../utils/api'

export default {
  name: 'TagEditableField',
  components: {
    TagSearchInput
  },
  props: {
    model: {
      type: Object,
      default: () => {}
    },
    size: {
      type: String,
      default: 'large',
      validator: value => ['small', 'large'].includes(value)
    },
    loading: {
      type: Boolean,
      default: false
    },
    hasPermission: {
      type: Boolean,
      default: true
    }
  },
  data () {
    return {
      dirtyValue: null,
      isEditable: false,
      isLoading: false,
      originalValue: null,
      showEditIcon: false,
      tagQuery: '',
      tags: [],
      preventSave: false
    }
  },
  computed: {
    value: {
      get () {
        return this.$get(this.model, 'tags', '') || []
      },
      set (value) {
        this.$set(this.model, 'tags', value)
      }
    },
    items () {
      if (this.dirtyValue && !this.$contains(this.tags, this.dirtyValue, 'name')) {
        return [...this.dirtyValue, ...this.tags]
      } else {
        return this.tags
      }
    }
  },
  watch: {
    tagQuery (value) {
      this.searchTags(value)
    },
    loading (newValue, oldValue) {
      if (oldValue && !newValue && this.isEditable) {
        this.isEditable = false
      }
    },
    value (value) {
      this.dirtyValue = value
    },
    isEditable (newValue, oldValue) {
      if (!oldValue && newValue) {
        this.dirtyValue = this.value
      }
    }
  },
  methods: {
    makeFieldEditable () {
      this.isEditable = true
      this.$nextTick(() => {
        this.$refs.edit.focus()
      })
      this.originalValue = this.value
    },
    makeFieldNotEditable () {
      if (!this.preventSave && this.$refs.edit.validate()) {
        if (this.originalValue !== this.dirtyValue) {
          this.$emit('update-value', { tags: this.dirtyValue })
        }
      }
      this.preventSave = false
    },
    async searchTags (value) {
      if (value) {
        this.isLoading = true
        const response = await fetchListRecords('tags', {
          search: value,
          limit: 5
        })
        let tags = response.results
        if (!tags.length) {
          tags = [{
            header: 'Add new tag:'
          }, {
            name: value
          }]
        }
        this.tags = tags
        this.isLoading = false
      }
    },
    onSelect (value) {
      this.dirtyValue = value
      this.preventSave = true
    },
    save (value) {
      this.preventSave = false
      this.makeFieldNotEditable()
    },
    remove (item) {
      this.dirtyValue = this.$remove(this.dirtyValue, item, 'name')
    },
    cancelEdition () {
      this.value = this.originalValue
      this.isEditable = false
    }
  }
}
</script>

<style lang="scss">
.tag-editable-field {
  font-size: 12px;
  margin: 0;
  margin-left: -30px;
  margin-right: 16px;
  margin-top: -12px;
  margin-bottom:  10px;
  input {
    padding: 0px;
  }
  .v-icon {
    font-size: 20px;
    margin-right: -15px;
    color: transparent;
    &:hover {
      color: rgba(0,0,0,.54);
    }
  }
  .v-input__icon--prepend .v-icon {
    margin-top: 8px;
  }
  .v-chip__content {
    padding: 0px 20px;
    height: 26px;
  }
}
.tag-chips {
  line-height: 43px;
  .v-input__control {
    margin-top: -9px;
  }
  .v-chip {
    height: 26px;
    padding: 0 12px;
    span {
      padding: 0
    }
  }
}
</style>
