<template>
<dl class="sortDrop" :id="id" v-on-clickaway="away">
    <dt @click="open = !open" :class="{'open': open}">{{displayText}} <Icon class="icon" :icon="['fabt', 'chevron-down']" :rotation="open ? 180 : null"/></dt>
    <dd v-show="open">
        <div class="type" v-show="type == 'SORTBY'">
            <button :class="{'active': order == 'ASC'}" @click="selectOrder('ASC')">{{$t('btgsvue.sorterLabel1')}}<Icon class="icon" :icon="['fabt', 'arrow-up']"/></button>
            <button :class="{'active': order == 'DESC'}" @click="selectOrder('DESC')">{{$t('btgsvue.sorterLabel2')}}<Icon class="icon" :icon="['fabt', 'arrow-down']"/></button>
        </div>
        <ul>
            <li v-for="o in optsList" @click="selectSort(o.value, o.label)" :key="o.value">{{o.label}}</li>
        </ul>
    </dd>
</dl>
</template>

<script>
import { find } from 'lodash'
import { mixin as clickaway } from 'vue-clickaway'
import { FontAwesomeIcon as Icon } from '@fortawesome/vue-fontawesome'
/**
* Generates the sorting control for the data table
*/
export default {
	name: 'SortControl',
	mixins: [clickaway],
	components: {
		Icon
	},
	props: {
        /**
        * Unique identifier
        */
		id: {
			type: String,
			required: true
		},
        /**
        * Object parameters to be sorted (csv value)
        */
		params: {
			default: '',
			type: String
		},
        /**
        * Corresponding labels to be shown for the passed params
        */
		labels: {
			default: '',
			type: String
		},
        /**
        * If the control to be used as SORTBY/GROUPBY
        */
		type: {
			default: 'SORTBY',
			type: String,
			validator: value => {
				return ['GROUPBY', 'SORTBY'].includes(value)
			}
		}
	},
	data() {
		return {
			selected: 'NO',
			order: 'ASC',
			optsList: [{ value: 'NO', label: 'Default Sort' }],
			open: false
		}
	},
	computed: {
		displayText() {
			let l = find(this.optsList, { value: this.selected }).label
			if (this.type === 'GROUPBY') {
				return (this.selected !== 'NO' ? this.$t('btgsvue.sorterText4', { val: l }) : this.$t('btgsvue.sorterText3'))
			} else {
				return (this.selected !== 'NO' ? this.$t('btgsvue.sorterText2', { val: `${l} (${this.order})` }) : this.$t('btgsvue.sorterText1'))
			}
		}
	},
	methods: {
		selectSort(p, l) {
			this.selected = p
			this.emitEvent()
		},
		selectOrder(p) {
			this.order = p
			if (this.selected != 'NO') {
				this.emitEvent()
			}
		},
		emitEvent() {
			if (this.type === 'SORTBY' && this.selected != 'NO') {
				this.$emit('input', `${this.selected}|${this.order}`)
			} else {
				this.$emit('input', this.selected)
			}
			this.away()
		},
		away() {
			this.open = false
		}
	},
	beforeMount() {
		let p = this.params.split(',')
		let l = this.labels.split(',')
		for (let i = 0; i < p.length; i++) {
			this.optsList.push({ value: p[i], label: l[i] })
		}
	},
	mounted() {
		this.$events.on(`sorter:${this.id}`, o => {
			this.selectSort(o.param, o.label)
		})
	}
}
</script>
