import type { Flair } from './FlairStore.svelte';
import { post } from './utils';

export type AsEnum<T> = T[keyof T];

export const ApplicationStatus = Object.freeze({
	ToApply: 0,
	WorkingOnIt: 1,
	Ignore: 2,
	ApplyedButSaidNo: 3,
	Applyed: 4,
	Expired: 5,
    TasksToDo: 6,
    LinkedApplication: 7
});

export const ApplicationStatusMaping: Record<
	(typeof ApplicationStatus)[keyof typeof ApplicationStatus],
	string
> = Object.freeze({
	0: 'To Apply',
	1: 'Working On It',
	2: 'Ignore',
	3: 'Applyed But Said No',
	4: 'Applyed',
	5: 'Expired',
    6: 'Tasks To Do',
    7: 'Linked Application',
});

export type View = {
    id: string,
    application_id: string,
    time: string,
}

export type Application = {
	id: string;
	url: string;
	original_url: string | null;
	unique_url: string | null;
	title: string;
	user_id: string;
	extra_data: string;
	payrange: string;
	status: AsEnum<typeof ApplicationStatus>;
    recruiter: string;
    company: string;
    message: string;
    linked_application: string;
    application_time: string;
    create_time: string;
    status_history: string;
	flairs: Flair[];
    views: View[];
};

function createApplicationStore() {
	let applications: Application[] = $state([]);
	let applyed: Application[] = $state([]);
	let tasksToDo: Application[] = $state([]);

	let dragApplication: Application | undefined = $state(undefined);

    let loadItem: Application | undefined = $state(undefined);

	return {
		/**
		 * @throws {Error}
		 */
		async loadApplications(force = false) {
			if (!force && applications.length > 1) {
				return;
			}
			applications = await post('application/list', { status: 0 });
		},

		/**
		 * @throws {Error}
		 */
		async loadAplyed(force = false) {
			if (!force && applyed.length > 1) {
				return;
			}
			applyed = await post('application/list', { status: ApplicationStatus.Applyed });
		},

		/**
		 * @throws {Error}
		 */
		async loadTasksToDo(force = false) {
			if (!force && tasksToDo.length > 1) {
				return;
			}
			tasksToDo = await post('application/list', { status: ApplicationStatus.TasksToDo });
		},

		clear() {
			applications = [];
		},

		dragStart(application: Application) {
			dragApplication = application;
		},

		dragEnd() {
			dragApplication = undefined;
		},

		get dragging() {
			return dragApplication;
		},

		get applications() {
			return applications;
		},

		get applyed() {
			return applyed;
		},

        get tasksToDo() {
            return tasksToDo;
        },

        get loadItem() {
            return loadItem;
        },

        set loadItem(item: Application | undefined) {
            loadItem = item;
        },
	};
}

export const applicationStore = createApplicationStore();
