<template>
  <div class="flex flex-wrap justify-center">
    <div
      id="page-content-wrapper"
      class="w-5/6 my-14"
    >
      <p>
        <b>
          CD-CODE is a comprehensive, manually curated database of biomolecular
          condensates and an encyclopedia of the scientific terms used to
          describe and characterize those condensates.
          {{ isDev ? "(Dev version)" : "" }}
        </b>
      </p>

      <div class="mt-20">
        <Search ref="search">
          <template slot-scope="{ response, loading }">
            <div v-if="loading">
              Loading...
            </div>
            <div v-else-if="response">
              <div v-show="response.count === 0">
                Seems like we could not understand what you were searching for,
                please go to the
                <router-link to="/proteins">
                  Protein list page
                </router-link> or
                <router-link to="/condensates">
                  Condensate list page
                </router-link>
              </div>
              <data-table
                v-show="response.count > 0"
                id="dataTable"
                :category="searchPick"
                :data="response.data"
                :keyword="keyword"
              />
            </div>
          </template>
        </Search>
      </div>
    </div>
  </div>
</template>

<script>
import Search from '@/components/Search.vue';
import DataTable from '@/components/DataTable.vue';

const _ = require('lodash');
const apikey = require('./js/const').apikey;

export default {
  name: 'SearchPage',
  components: {
    Search,
    DataTable,
  },
  props: {
    msg: String,
  },
  data() {
    return {
      selected: '',
      keyword: this.$route.params.keyword,
      species: 'All',
      searchKeyword: '',
      pick: 'protein',
      searchPick: '',
      isDev: process.env.NODE_ENV === 'development',
    };
  },
  mounted() {
    // console.log(this.keyword)
    // console.log(this.$route)
    // console.log(this.$route.query)
    // console.log(this.$route.query.q)
    this.searchWithKeyword(
      this.$route.query.q,
      this.$route.query.t,
      this.$route.query.s
    );
  },
  methods: {
    removeNullItems(data) {
      return _.filter(data, (d) => d._id !== null);
    },
    getSuggestionList() {
      const vm = this;

      const query = vm.keyword;

      let host = vm.isDev
        ? require('./js/const').devHost
        : require('./js/const').host;
      const taxId =
        vm.species === 'All' ? 'all' : /\((\d+)\)$/gm.exec(vm.species)[1];
      let url =
        vm.species === 'All'
          ? `${host}/${vm.pick}s?query=${query}&size=10000`
          : `${host}/${vm.pick}s?query=${query}&species_tax_id=${taxId}&size=10000`;

      // console.log(process.env.VUE_APP_TITLE)
      // console.log(process.env.VUE_APP_API_KEY)

      return fetch(url, {
        method: 'GET',
        mode: 'cors',
        cache: 'no-cache',
        headers: {
          Authorization: `Bearer ${apikey}`,
        },
      })
        .then((response) => response.json())
        .then((json) => _.uniq(_.map(json.data, (c) => c.gene_name || c.name)));
    },
    searchWithKeyword(q, t, s) {
      const vm = this;
      // const page = 1;
      // console.log(`http://${host}/proteins?query=${vm.keyword}&species_tax_id=${taxId}&page=${page}`)
      vm.keyword = q;
      // console.log(vm.pick)

      vm.searchPick = t;
      if (t === 'protein') {
        if (q.includes('(')) {
          const id = /\((\S*)\)/gm.exec(q)[1];
          const url = `/protein/${id}`;

          vm.$router.replace({
            name: 'home',
            query: {
              q: '',
              t: vm.pick,
              s: s,
            },
          });

          // eslint-disable-next-line
          vm.$router.push(url);
        } else {
          vm.$refs.search.fetchProteinList(q, s);
        }
      } else if (t === 'condensate') {
        if (q.includes('(')) {
          const id = /\((\S*)\)/gm.exec(q)[1];
          const url = `/condensate/${id}`;

          vm.$router.replace({
            name: 'home',
            query: {
              q: '',
              t: vm.pick,
              s: s,
            },
          });

          // eslint-disable-next-line
          vm.$router.push(url);
        } else {
          vm.$refs.search.fetchCondensateList(q, s);
        }
      }
      // /* eslint-disable no-console */
      // console.log(this.searchKeyword)
    },
  },
};
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
@import url("~@/assets/bootstrap.css");
@import url("~@/assets/datatable.css");
@import url("~@/assets/vue-simple-suggest-styles.css");

.main {
  margin: 1.5rem;
}

h3 {
  margin: 40px 0 0;
}

a {
  color: #ef0087 !important;
}

input[type="radio"] {
  margin: 2px;
}

.radio-label {
  margin-left: 0px;
  margin-right: 5px;
}
</style>