import type { SortDirectionsT, SortingOptions } from '../../types/TableSchema'
import { ref, computed } from 'vue'

export function useSorting(options: SortingOptions) {
	const sortFieldRef = ref('')
	const sortDirectionRef = ref<SortDirectionsT>('ASC')

	const sortField = computed(() => sortFieldRef.value)
	const sortDirection = computed(() => sortDirectionRef.value)

	function sort(fieldname: string) {
		if (sortFieldRef.value === fieldname) {
			if (sortDirectionRef.value === 'ASC') {
				sortDirectionRef.value = 'DESC'
			} else {
				sortFieldRef.value = ''
			}
		} else {
			sortFieldRef.value = fieldname
			sortDirectionRef.value = 'ASC'
		}
		options.onSort(sortFieldRef.value, sortDirectionRef.value)
	}

	return {
		sortField,
		sortDirection,
		sort
	}
}
