import React from "react";

import { buildEmptyObject } from "../../../../auto/js/widgets/FormComponent";
import { getServiceUri, pojoMetadata } from "../../../../auto/js/metadata";
import { MTLB_TYPE_DIVORCE } from "../../../../auto/js/metadata/MtlbType";
import { rest, t } from "../../../../auto/js/services";
import { showNotification } from "../../../../auto/js/utils";
import { MTLB_STATUS_SUBMITTED } from "../../../../auto/js/metadata/MtlbStatus";
import { DELETE_ATTACHMENT_EVENT } from "../../../../auto/js/events/Gui";
import { Section } from "../../../../auto/js/widgets/Section";

export const divorceRegistrationFields = [
    {name: "tags", type:"tags", x:1, y:1, layout:"col-md-12"},
    {name: "unionRecordId", type: "number", x:1, y:2, layout:"col-md-12", disabled: true},
    {name: "dateOfEffect", type: "date", x:1, y:3, layout:"col-md-6"},
    {name: "dateOfOrder", type: "date", x:2, y:3, layout:"col-md-6"},
    {name: "courtOrderFile", label:"Court Order", type: "file", x:1, y:25, layout:"col-md-12", 
		uploadUrl: (id) => getUploadUrl(id), 
        previewUrl: async (id) => getPreviewUrl(id),
		loadData: async (id) => loadCourtOrder(id), 
		handleDelete:(id) => handleCourtOrderDelete(id), 
		handleClick: (id) => handleCourtOrderClick(id),
		updateFileData: (data) => updateFileData(data)
	},
    {name: "Mentions", type: "custom", x:1, y:29, layout:"col-md-12", component: (name, disabled) => <Section name={name} />},
    {name: "mentions", type: "text", x:1, y:30, layout:"col-md-12"},
    {name: "Extras", type: "custom", x:1, y:31, layout:"col-md-12", component: (name, disabled) => <Section name={name} />},
    {name: "notes", type: "text", x:1, y:32, layout:"col-md-12"}
];

const getUploadUrl = (id) => {
	return getServiceUri() + 'union-mtlb/court-order-file' + '/' + id;
}

const getPreviewUrl = async (id) => {
    const token = await rest.getToken(getServiceUri() + 'token/get-auth-code');
	return getServiceUri() + 'union-mtlb/court-order-file' + '/preview/' + id + '/' + token;
}

const updateFileData = (data) => {
	let filter = {name: data.fileName, description: data.description};
	rest.request(getServiceUri() + 'union-mtlb/court-order-file' + '/' + data.id, "PUT", filter);
}

const handleCourtOrderClick = async (id) => {
	const token = await rest.getToken(getServiceUri() + 'token/get-auth-code');
	window.location = getServiceUri() + 'union-mtlb/court-order-file' + '/' + id + '/' + token;
};
const handleCourtOrderDelete = (id) => {
	rest.delete('union-mtlb/court-order-file', id).then(() => {
		DELETE_ATTACHMENT_EVENT.publish(id)
	});
};

const loadCourtOrder = async (id) => {
	let filter = {and: true};
	filter['union-mtlb-court-order-file'] = {};
	filter['union-mtlb-court-order-file']['unionMtlbId'] = id;
	return rest.search('union-mtlb/court-order-file', filter)
}

export const saveDivorceRegistrationForm = async (formData) => {
    let dto = pojoMetadata['union-mtlb'].form2dto(formData);
    dto.mtlbType = MTLB_TYPE_DIVORCE;
    try {
        return rest.request(getServiceUri() + 'union-mtlb', 'POST', dto)
    } catch (err) {
        alert(err);
    }
}

export const loadDivorceRegistrationFormData = async (id) => {
    return await rest.read('union-mtlb', id).then(response => {
        let form = response;
        let tagFilter = {and: true};
        tagFilter['union-mtlb-tag'] = {unionMtlbId: id};
        if (response.status)
            showNotification(response.message.split('Detail: ')[1], "error")
        
        return rest.search('union-mtlb-tag', tagFilter).then(tags => {
            form['tags'] = tags
            
            return form;
        })
    })
}

export const updatePendingDivorceRegistrationForm = async (formData) => {
    let dto = pojoMetadata['union-mtlb'].form2dto(formData);
    try {
        return rest.request(getServiceUri() + 'union-mtlb/pending/update', 'POST', dto);
    } catch (err) {
        alert(err);
    }
}

export const updateRejectedDivorceRegistrationForm = async (formData) => {
    let dto = pojoMetadata['union-mtlb'].form2dto(formData);
    try {
        return rest.request(getServiceUri() + 'union-mtlb/rejected/update', 'POST', dto);
    } catch (err) {
        alert(err);
    }
}

export const rejectDivorceRegistrationForm = async (id) => {
    try {
        return rest.request(getServiceUri() + 'union-mtlb/pending/reject', 'POST', id);
    } catch (err) {
        alert(err);
    }
}

export const buildDivorceRegistrationFormEmptyObject  = () => {
    const empty = buildEmptyObject(divorceRegistrationFields);
    return empty;
}

export const updateDivorceRegistrationForm = async (formData) => {
    let dto = pojoMetadata['union-mtlb'].form2dto(formData);
    dto.mtlbStatus = MTLB_STATUS_SUBMITTED;
    dto.draft = false;
    try {
        return rest.update('union-mtlb', dto);
    } catch (err) {
        alert(err);
    }
}

export const deleteDivorceRegistrationForm = async (id) => {
    try {
        return rest.delete('union-mtlb', id);
    } catch (err) {
        alert(err);
    }
}

export const form2dto = (formData, dto) => {
	dto.mtlbType = MTLB_TYPE_DIVORCE;
	if(formData.dateOfEffect != null && typeof(formData.dateOfEffect) != 'string') {
		let dateOfEffectAsDate = new Date(formData.dateOfEffect);
		dto.dateOfEffect = dateOfEffectAsDate.getFullYear() + "-" + ('0' + (dateOfEffectAsDate.getMonth() + 1)).slice(-2) + "-" + ('0' + dateOfEffectAsDate.getDate()).slice(-2);
	}
    if(formData.dateOfOrder != null && typeof(formData.dateOfOrder) != 'string') {
		let dateOfOrderAsDate = new Date(formData.dateOfOrder);
		dto.dateOfOrder = dateOfOrderAsDate.getFullYear() + "-" + ('0' + (dateOfOrderAsDate.getMonth() + 1)).slice(-2) + "-" + ('0' + dateOfOrderAsDate.getDate()).slice(-2);
	}
}

export const dto2form = (response) => {
	return response;
    
}

export const newDivorceRegistrationFormForm2Dto = (form, dto) => {
    dto.mtlbType = MTLB_TYPE_DIVORCE;
    dto.unionRecordId = form.id;
    dto.id = null;
    dto.timeOfMarriage = null;
}