<template>
  <v-container>
    <v-layout row wrap class="home-search-input">
      <v-flex xs6 offset-xs3 class="home-search-btn">
        <v-autocomplete
          ref="input"
          v-model="select"
          :loading="loading"
          :items="items"
          :search-input.sync="searchText"
          append-icon="search"
          placeholder="Search by: project, patients, application or keywords."
          class="home-search mt-1 ml-1"
          content-class="home-search-results"
          autofocus
          light
          hide-details
          hide-no-data
          no-filter
          @change="onSelect"
          @keyup.enter.prevent="search"
          @keyup.esc="clearText"
          @blur="keepFocus">

          <template
            slot="item"
            slot-scope="{ item, tile }">

            <template v-if="item.type==='projects'">
              <v-list-tile-avatar
                color="primary"
                class="subheading font-weight-light white--text">
                {{ item.pk }}
              </v-list-tile-avatar>

              <v-list-tile-content>
                <v-list-tile-title>
                  <b>Project </b> {{ item.title  | truncate(30)}}
                </v-list-tile-title>
                <v-list-tile-sub-title>
                  {{ item.description | truncate(80) }}
                </v-list-tile-sub-title>
              </v-list-tile-content>
            </template>

            <template v-else-if="item.type==='analyses'">
              <v-list-tile-avatar
                color="primary"
                class="subheading font-weight-light white--text">
                {{ item.status.charAt(0) }}
              </v-list-tile-avatar>

              <v-list-tile-content>
                <v-list-tile-title>
                  <b>Analysis </b> {{ item.application.name }}
                </v-list-tile-title>
                <v-list-tile-sub-title>
                  <span :class="`status-${item.status.toLowerCase()}`">
                    {{ item.status }}
                  </span> - {{ item.modified | formatDate('calendar') }}
                </v-list-tile-sub-title>
              </v-list-tile-content>
            </template>

            <template v-else-if="item.type === 'individuals'">
              <v-list-tile-avatar
                color="primary"
                class="subheading font-weight-light white--text">
                {{ item.species.charAt(0) }}
              </v-list-tile-avatar>
              <v-list-tile-content>
                <v-list-tile-title>
                  <b>Individual </b> {{ item.system_id }}
                </v-list-tile-title>
                <v-list-tile-sub-title>
                  ID: {{ item.research_id }} - {{ item.gender }}
                </v-list-tile-sub-title>
              </v-list-tile-content>
            </template>

            <template v-else-if="item.type === 'samples'">
              <v-list-tile-avatar
                color="primary"
                class="subheading font-weight-light white--text">
                {{ item.individual.species.charAt(0) }}
              </v-list-tile-avatar>
              <v-list-tile-content>
                <v-list-tile-title>
                  <b>Sample </b> {{ item.system_id }}
                </v-list-tile-title>
                <v-list-tile-sub-title>
                  ID: {{ item.research_id }} - {{ item.sample_class }}
                </v-list-tile-sub-title>
              </v-list-tile-content>
            </template>

            <template v-else-if="item.type === 'experiments'">
              <v-list-tile-avatar
                color="primary"
                class="subheading font-weight-light white--text">
                {{ item.sample.individual.species.charAt(0) }}
              </v-list-tile-avatar>
              <v-list-tile-content>
                <v-list-tile-title>
                  <b>Experiment </b> {{ item.system_id }}
                </v-list-tile-title>
                <v-list-tile-sub-title>
                  ID: {{ item.research_id }} - {{ Object.keys(item.data).join(", ") }}
                </v-list-tile-sub-title>
              </v-list-tile-content>
            </template>

            <template v-else-if="item.type==='submissions'">
              <v-list-tile-avatar
                color="primary"
                class="subheading font-weight-light white--text">
                {{ item.pk }}
              </v-list-tile-avatar>

              <v-list-tile-content>
                <v-list-tile-title>
                  <b>Submission </b>
                  <span v-if="getSubmissionErrors(item).length">
                    <span
                      v-for="(errorMessage, index) in getSubmissionErrors(item)"
                      :key="index">
                      {{ errorMessage | truncate(20) }}
                    </span>
                  </span>
                  <span v-else-if="$get(item, 'data.summary')">{{ $get(item, 'data.summary') }}</span>
                </v-list-tile-title>
                <v-list-tile-sub-title>
                  For Project <b>{{ item.projects[0] }}</b> - {{ item.description | truncate(40) }}
                </v-list-tile-sub-title>
              </v-list-tile-content>
            </template>

          </template>

        </v-autocomplete>
      </v-flex>
    </v-layout>
  </v-container>
</template>

<script>
import { fetchListRecords } from '@/utils/api'
import { SHOW_PANEL } from '@/store/actions/panels'
import _ from 'lodash'

export default {
  name: 'HomeSearch',
  data () {
    return {
      loading: false,
      searchText: null,
      select: null,
      searchResults: {
        projects: {},
        analyses: {},
        individuals: {},
        samples: {},
        experiments: {},
        submissions: {}
      },
      preventGlobalSearch: false
    }
  },
  computed: {
    permanentFocus () {
      return this.$store.getters.areAllModalsHidden
    },
    items () {
      return Object.values(this.searchResults).filter(model => {
        return Object.keys(model).length
      })
    }
  },
  watch: {
    searchText (value) {
      value && value !== this.select && this.debouncedEmit()
    }
  },
  created () {
    this.debouncedEmit = _.debounce(this.queryModels, 300)
  },
  methods: {
    onSelect (selected) {
      const models = {
        'projects': 'project',
        'analyses': 'analysis',
        'individuals': 'bioModel',
        'samples': 'bioModel',
        'experiments': 'bioModel',
        'submissions': 'submission'
      }
      const model = models[selected.type]
      const value = model === 'bioModel' ? selected.system_id : selected.pk
      this.$store.dispatch(SHOW_PANEL, { [model]: value })
      this.preventGlobalSearch = true
    },
    clearText () {
      this.searchText = undefined
    },
    search () {
      if (!this.preventGlobalSearch) {
        this.$store.dispatch(SHOW_PANEL, { search: this.searchText })
      }
    },
    keepFocus () {
      this.permanentFocus && this.$refs.input.focus()
    },
    queryModels () {
      const search = this.searchText
      Object.keys(this.searchResults).forEach(model => {
        fetchListRecords(model, {
          search,
          limit: 1
        }).then(response => {
          if (response.results && response.results.length) {
            this.searchResults[model] = response.results[0]
            this.searchResults[model].type = model
          } else {
            this.searchResults[model] = {}
          }
        }).catch(() => {
          this.searchResults[model] = {}
        })
      })
    },
    getSubmissionErrors (item) {
      let errors = []
      if (this.$get(item, 'data.errors', []).length) {
        item.data.errors.forEach(error => {
          Object.keys(error).forEach(type => {
            if (typeof error[type] !== 'string') {
              error[type].forEach(errorType => {
                errors.push(errorType)
              })
            }
          })
        })
      }
      return errors
    }
  }
}
</script>

<style lang="scss">
.home-search {
  input::placeholder {
    font-size: 26px;
  }
  i {
    transform: none !important;
  }
}
.home-search-results {
  &.v-menu__content {
    max-height: 600px !important;
    overflow-y: hidden
  }
  .v-list__tile {
    height: 60px;
  }
}
.home-search-input {
  margin-top: 25vh !important;
}
.home-search-input .v-input {
  font-size: 40px;
  input {
    max-height: 1.2em;
  }
  .v-text-field__slot {
    margin-bottom: 10px;
  }
  label {
    font-size: 25px;
    height: 1em;
    margin-top: 16px;
  }
  .v-icon {
    font-size: 40px;
    margin-top: 30px;
  }
}

</style>
