<template>
	<div className="card">
		<DataTable v-model:filters="filters" :value="ksdocuments" paginator showGridlines :rows="10" dataKey="id"
			filterDisplay="menu" :loading="loading"
			:globalFilterFields="['name', 'fileName', 'ingestionStatus', 'ingestionDateFormat']">
			<template #header>
				<div class="flex items-center justify-between gap-4 p-4 ">
					<span class="text-xl font-bold">KS Documents</span>
					<div class="flex items-center gap-2 flex-grow">
						<IconField class="flex-grow">
							<InputIcon>
								<i class="pi pi-search" />
							</InputIcon>
							<InputText v-model="filters['global'].value" placeholder="Keyword Search" />
						</IconField>
					</div>
					<Button icon="pi pi-plus" rounded raised @click="newKsDocument()" v-tooltip="'Create New Document'"
						class="mr-2" />
					<Button icon="pi pi-check-circle" rounded raised @click="startlngestion()"
						v-tooltip="'Start All documents Ingestion'" class="mr-8" :disabled="allDocumentsIngested"
						:class="{ 'p-button-danger': allDocumentsIngested }" />
				</div>
			</template>
			<template #empty>No Records found</template>
			<template #loading>Loading Data. Please wait....</template>
			<Column field="id" header="ksdocuments id" sortable style="min-width: 12rem" />
			<Column field="ingestionInfo.id" header="ksingestioninfo id" sortable style="min-width: 12rem" />
			<Column field="name" header="Name" sortable style="min-width: 12rem">
				<template #body="{ data }">
					{{ data.name }}
				</template>
				<template #filter="{ filterModel, filterCallback }">
					<InputText v-model="filterModel.value" type="text" @input="filterCallback()" placeholder="Search by File" />
				</template>
			</Column>
			<Column field="fileName" header="File Name" sortable>
				<template #body="{ data }">
					{{ data.fileName }}
				</template>
				<template #filter="{ filterModel, filterCallback }">
					<InputText v-model="filterModel.value" type="text" @input="filterCallback()"
						placeholder="Search by File Name" />
				</template>
			</Column>
			<Column field="ingestionStatus" header="Status" sortable>
				<template #body="slotProps">
					<Tag :value="slotProps.data.ingestionStatus" :severity="getStatus(slotProps.data)" />
				</template>
				<template #filter="{ filterModel, filterCallback }">
					<Select v-model="filterModel.value" @change="filterCallback()" :options="statuses" placeholder="Select One"
						style="min-width: 12rem" :showClear="true">
						<template #option="{ option }">
							<Tag :value="option" :severity="getStatus({ ingestionStatus: option })" />
						</template>
					</Select>
				</template>
			</Column>
			<Column header="Ingestion Date" filterField="ingestionDateFormat" dataType="date" style="min-width: 10rem">
				<template #body="{ data }">
					{{ formatDate(data.ingestionDate) }}
				</template>
				<template #filter="{ filterModel }">
					<DatePicker v-model="filterModel.value" dateFormat="mm/dd/yy" placeholder="mm/dd/yyyy"
						@change="updateFilterModel" />
				</template>
			</Column>
			<Column headerStyle="width: 5rem; text-align: center" bodyStyle="text-align: center; overflow: visible">
				<template #body="slotProps">
					<div class="flex justify-center items-center">
						<Button type="button" icon="pi pi-pencil" rounded @click="editKsDocument(slotProps.data)"
							v-tooltip="'Edit the information of document'" class="mr-4" />
						<!--Tag :value="slotProps.data.id" /-->
						<!--Tag :value="slotProps.data.ingestionInfo.id" /-->
						<!--Button type="button" v-if="slotProps.data.ingestionStatus === 'NEW'" icon="pi pi-play" rounded
                        @click="startIndividualngestion(slotProps.data.id)" v-tooltip="'Start Ingestion of document'" class="mr-4" /-->
						<Button type="button" icon="pi pi-play" rounded @click="startIndividualngestion(slotProps.data.id)"
							v-tooltip="'Start Ingestion of document'" :disabled="slotProps.data.ingestionStatus === 'INGESTED'"
							:class="{ 'p-button-danger': slotProps.data.ingestionStatus === 'INGESTED' }" class="mr-7" />
					</div>
				</template>
			</Column>
		</DataTable>
		<Dialog header="Ingestion Result" v-model:visible="ingestionDialogVisible" :modal="true" :closable="false">
			<p>{{ ingestionResult }}</p>
			<Button label="OK" icon="pi pi-check" @click="ingestionDialogVisible = false" />
		</Dialog>
	</div>
</template>

<script setup>
import { FilterMatchMode, FilterOperator } from '@primevue/core/api';
import axios from 'axios';
import { computed, onMounted, ref } from 'vue';
import { useRouter } from 'vue-router';
import moment from 'moment';

import Button from 'primevue/button';
import Column from 'primevue/column';
import DataTable from 'primevue/datatable';
import DatePicker from 'primevue/datepicker'
import Dialog from 'primevue/dialog';
import InputText from 'primevue/inputtext';
import Select from 'primevue/select';
import Tag from 'primevue/tag';
import Tooltip from 'primevue/tooltip';


const router = useRouter()
const ksdocuments = ref(null);
const loading = ref(true);

const ingestionDialogVisible = ref(false);
const ingestionResult = ref('');
const filters = ref();

const initFilters = () => {
	filters.value = {
		global: { value: null, matchMode: FilterMatchMode.CONTAINS },
		id: { operator: FilterOperator.AND, constraints: [{ value: null, matchMode: FilterMatchMode.EQUALS }] },
		name: { operator: FilterOperator.AND, constraints: [{ value: null, matchMode: FilterMatchMode.STARTS_WITH }] },
		fileName: { operator: FilterOperator.AND, constraints: [{ value: null, matchMode: FilterMatchMode.STARTS_WITH }] },
		ingestionDateFormat: { operator: FilterOperator.AND, constraints: [{ value: null, matchMode: FilterMatchMode.DATE_IS }] },
		ingestionStatus: { operator: FilterOperator.OR, constraints: [{ value: null, matchMode: FilterMatchMode.EQUALS }] }
	};
};

initFilters();

const statuses = ref(['NEW', 'INGESTED', 'FAILED']); // Add your statuses here

onMounted(() => {
	axios.get('http://localhost:8082/fe-api/ksdocuments')
		.then(response => {
			ksdocuments.value = getCustomDatewithAllResponse(response.data);
			console.log(ksdocuments.value);
			loading.value = false;
		});
});

// Computed property to check if all documents are ingested
const allDocumentsIngested = computed(() => {
	return ksdocuments.value && ksdocuments.value.every(doc => doc.ingestionStatus === 'INGESTED');
});


const getStatus = (data) => {
	if (data.ingestionStatus === 'INGESTED') {
		return 'success';
	} else if (data.ingestionStatus === 'NEW') {
		return 'danger';
	} else {
		return 'warn';
	}
}

const getCustomDatewithAllResponse = (data) => {
	return [...(data || [])].map((d) => {
		d.ingestionDateFormat = new Date(d.ingestionDateFormat);
		return d;
	});
};

const updateFilterModel = () => {
	console.log("updateFilterModel")
}

const editKsDocument = (data) => {
	console.log(data);
	router.push({ name: 'ks-document-edit', params: { id: data.id } });
}

const startIndividualngestion = (id) => {
	axios.get(`http://localhost:8082/test/ingest_document/${id}`)
		//axios.get('http://localhost:8082/test/ingestion_loop')
		.then(response => {
			ingestionResult.value = response.data;
			if (response.data.status == "OK") {
				ksdocuments.value.forEach(element => {
					if (response.data.ingestedDocumentId.includes(element.id)) {
						element.status = "INGESTED"
					}
				});
			} else {
				ingestionResult.value = `Error: ${response.data.message}`;
			}

			ingestionDialogVisible.value = true;
		})
		.catch(error => {
			ingestionDialogVisible.value = true;
		});
};

const startlngestion = () => {
	axios.get('http://localhost:8082/test/ingestion_loop')
		.then(response => {
			ingestionResult.value = response.data;
			if (response.data.status == "OK") {
				ksdocuments.value.forEach(element => {
					if (response.data.ingestedDocumentId.includes(element.id)) {
						element.status = "INGESTED"
					}
				});
			} else {
				ingestionResult.value = `Error: ${response.data.message}`;
			}

			ingestionDialogVisible.value = true;
		})
		.catch(error => {
			ingestionDialogVisible.value = true;
		});
};

const newKsDocument = () => {
	console.log('new');
	router.push({ name: 'ks-document-new' });

}

// Function to format date string
function formatDate(dateString) {
	// Parse the date string using moment
	return moment(dateString).format('MM/DD/YYYY');
}

</script>

<style scoped>
/* Custom styling for disabled red button */
.p-button-danger {
	background-color: red;
	border-color: red;
	color: white;
}

.p-button-danger:disabled {
	background-color: red;
	border-color: red;
	color: white;
	cursor: not-allowed;
}
</style>
