<!--
   Copyright 2018 Brigham Young University

   Licensed under the Apache License, Version 2.0 (the "License")
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
-->
<template>
  <div class="overflow-scroll">
    <div v-if="loading">
      <Spinner text="Loading Report..." />
    </div>

    <template v-else-if="error">
      <p>Error loading report.</p>
    </template>
    <template v-else-if="rows.length === 0">
      <p>No results returned.</p>
    </template>
    <template v-else>
      <div class="left-align-fullwidth">
        <FilterButton
          v-for="{ values, label, column } of uniqueValues"
          :key="label"
          @show="setFilterOpen(column)"
          @hide="setFilterClosed(column)"
          :show="filterOpen[column]"
        >
          <span slot="label">{{ label }}</span>
          <div @click="filterBy(null, column)" class="dropdown-item">All</div>
          <div
            v-for="val of values"
            :key="val"
            class="dropdown-item"
            @click="filterBy(val, column)"
          >
            {{val | yearTermLongFormat}}
          </div>
        </FilterButton>
        <span>
          <input type="checkbox" v-model="showHidden" id="showHiddenCheckbox">
          <label for="showHiddenCheckbox">Show sensitive columns</label>
        </span>
      </div>
      <div class="lr-fullwidth">
        <a :href="csvDataEncoded"
           :download="title ? `${title}.csv` : 'report.csv'"
           ><FontAwesomeIcon :icon="csvIcon" />Download as .csv</a>
        <span>
          {{ rowCount }} rows
        </span>
      </div>
      <table class="table table-hover table-bordered table-sm">
        <thead v-if="columnMetadata.length > 0">
          <tr>
            <template v-for="({meta}, i) of filterColumns(columnMetadata, showHidden)">
              <SortableHeader
                v-if="meta.qualifier.includes('sort')"
                :sort="sortColumnIndex"
                :field="i"
                :order="sortOrder"
                @click="sortBy(i)"
              >
                {{ meta.name }}
              </SortableHeader>
              <th v-else>
                {{ meta.name }}
              </th>
            </template>
          </tr>
        </thead>
        <tbody>
          <tr v-for="r of filteredRows">
            <td v-for="({meta, value}, i) of filterColumns(r, showHidden)">
              <!-- TODO: these apply to the wrong column if some columns are hidden! -->
              <template v-if="meta.qualifier.includes('link_app')">
                <router-link v-if="newTab" :to="replaceLinkValue(meta.link, value)" target="_blank" data-disable-navigate="true"> Application Details </router-link>
                <router-link v-else :to="replaceLinkValue(meta.link, value)"> Application Details </router-link>
              </template>
              <template v-else-if="meta.qualifier.includes('link_report')">
                <router-link v-if="newTab" :to="replaceLinkValue(meta.link, value)" target="_blank" data-disable-navigate="true">{{value}}</router-link>
                <router-link v-else :to="replaceLinkValue(meta.link, value)">{{value}}</router-link>
              </template>
              <template v-else-if="meta.qualifier.includes('date')">{{value | dateFormat}}</template>
              <template v-else-if="meta.qualifier.includes('timestamp')">{{value | dateTimeFormat}}</template>
              <template v-else-if="meta.qualifier.includes('admitPeriod')">{{value | yearTermLongFormat}}</template>
              <template v-else>{{value}}</template>
            </td>
          </tr>
        </tbody>
      </table>
    </template>
  </div>
</template>
<script>
import isIsoDate from 'is-iso-date'
import { dateFormat, dateTimeFormat, yearTermLongFormat } from './dateTimeFormat'
import FilterButton from './FilterButton'
import SortableHeader from './SortableHeader'
import Spinner from './Spinner'

import { FontAwesomeIcon } from '@fortawesome/vue-fontawesome'
import { faFileCsv } from '@fortawesome/free-solid-svg-icons'

export default {
  name: 'ReportDetail',
  components: {
    FilterButton,
    FontAwesomeIcon,
    SortableHeader,
    Spinner
  },
  filters: { dateTimeFormat, dateFormat, yearTermLongFormat },
  props: {
    columnMetadata: {
      type: Array,
      default: () => []
    },
    rows: {
      type: Array,
      default: () => []
    },
    csv: String,
    title: String,
    loading: Boolean,
    detailPath: {
      type: String,
      default: '/detail'
    },
    error: Boolean,
    newTab: Boolean
  },
  data () {
    return {
      appIdIndex: null,
      sortColumnIndex: null,
      sortOrder: 'desc',
      filteredRows: null,
      filterOpen: [],
      uniqueValues: null,
      showHidden: false
    }
  },
  watch: {
    rows: {
      handler: 'copyForFiltering',
      immediate: true
    }
  },
  computed: {
    csvDataEncoded () {
      const encoded = window.encodeURIComponent(this.csv)
      return `data:text/csv;charset=utf-8,${encoded}`
    },
    rowCount () {
      return this.rows.length
    },
    csvIcon () {
      return faFileCsv
    }
  },
  methods: {
    isIsoDate,
    isUuid (val) {
      const uuidPattern = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i
      return uuidPattern.test(val)
    },
    sortBy (i) {
      if (i === this.sortColumnIndex) {
        const order = this.sortOrder
        this.sortOrder = (order === 'desc') ? 'asc' : 'desc'
      } else {
        this.sortColumnIndex = i
        this.sortOrder = 'desc'
      }
      const sortDesc = (a, b) => {
        const valA = a[i]
        const valB = b[i]
        return valA > valB ? 1 : -1
      }
      const sortAsc = (a, b) => {
        const valA = a[i]
        const valB = b[i]
        return valA > valB ? -1 : 1
      }
      this.filteredRows.sort((this.sortOrder === 'desc') ? sortDesc : sortAsc)
    },
    copyForFiltering (rows) {
      if (Array.isArray(rows) && rows.length > 0) {
        this.filteredRows = rows.slice(0)
        this.uniqueValues = this.columnMetadata
          .map((meta, i) => {
            return {
              column: i,
              label: meta.name,
              values: this.unique(rows, i),
              columnCanBeFiltered: Array.isArray(meta.qualifier) ? meta.qualifier.includes('filter') : false
            }
          })
          .filter(o => o.columnCanBeFiltered)
          .filter(u => u.values.length < rows.length && u.values.length > 1)
      } else {
        this.filteredRows = null
        this.uniqueValues = null
      }
    },
    unique (rows, column) {
      const values = Array.from(rows.reduce((a, c) => {
        a.add(c[column])
        return a
      }, new Set())).sort()
      return values
    },
    filterBy (val, column) {
      this.filterOpen[column] = false
      if (val === null) {
        this.filteredRows = this.rows.slice(0)
      } else {
        this.filteredRows = this.rows.filter(r => r[column] === val)
      }
      this.sortOrder = 'desc'
      this.sortColumnIndex = null
    },
    setFilterOpen (col) {
      this.$set(this.filterOpen, col, true)
    },
    setFilterClosed (col) {
      this.$set(this.filterOpen, col, false)
    },
    filterColumns(data, showHidden) {
      const emptyMetadata = {
        ordinal: 999,
        name: '',
        qualifier: [],
        link: ''
      }
      const withMetadata = data.map((v, i) => ({ meta: this.columnMetadata[i] || emptyMetadata, value: v }))
      if(showHidden) {
        return withMetadata
      }
      const columnQualifierHidden = this.columnMetadata.map(m => {
        if(m.qualifier && Array.isArray(m.qualifier)) {
          return m.qualifier.includes('hidden')
        }
        return false;
      })
      return withMetadata.filter((val, i) => !columnQualifierHidden[i])
    },
    replaceLinkValue(link, value) {
      return link.replace(/:value/, value)
    }
  }
}
</script>

<style scoped>
  .left-align-fullwidth {
    display: flex;
  }
  .left-align-fullwidth > * {
    padding: 0.1rem 0.5rem;
  }
  .lr-fullwidth {
    display: flex;
    justify-content: space-between;
  }
  .overflow-scroll {
    max-height: 80vh;
    overflow: scroll;
  }
</style>
