const db = require("../models");
const Vehicle = db.vehicle;
const Customer = db.customer;
const CalendarEvent = db.calendar_event;
const moment = require('moment');
const siteMap = {
	'ws1': 1,
	'worldshine1': 1,
	'ws2': 2,
	'worldshine2': 2,
	'ws3': 3,
	'worldshine3': 3,
	'worldshine4': 4,
	'ws4': 4,
	'worldshine.mayo.llc': 1
};

const getSite = () => {
	console.log('here', __dirname);
	let site = 1;
	const arr = __dirname.split('/');
	for (const key of Object.keys(siteMap)) {
		if (arr.includes(key)) {
			site = siteMap[key];
			break;
		}
	}
	return site;
}

class ReminderService {
	parseDate(dateString) {
		const [month, day, year] = dateString.split('/').map(Number);
		return new Date(year, month-1,day);
	}

	async createVehicleRelatedEvents(daysAhead = 30) {
		const today = new Date();
		const futureDate = new Date();
		futureDate.setDate(today.getDate() + daysAhead); // check 30 days ahead

		const vehicles = await Vehicle.find({status: 'active', site: getSite()});
		const allVehiclesCalendarEvent = await CalendarEvent.find({type: 'reminder', status: 'active', site: getSite(), target_type: 'vehicle'});
		console.log('vehicles', vehicles);
		for (const vehicle of vehicles) {
			const insuranceExpireDate = this.parseDate(vehicle.insurance_expire_on);
			const titleRegistrationDate = this.parseDate(vehicle.title_registration_on);
			const titleExpireDate = new Date(titleRegistrationDate);
			titleExpireDate.setFullYear(titleExpireDate.getFullYear() + 1);
			const emissionTestDate = this.parseDate(vehicle.emission_test_on);
			const emissionTestExpireDate = new Date(emissionTestDate);
			emissionTestExpireDate.setFullYear(titleExpireDate.getFullYear() + 1);
			const newDate = new Date(insuranceExpireDate);
			newDate.setDate(newDate.getDate() - 15);
			const newDate1 = new Date(emissionTestExpireDate);
			newDate1.setDate(newDate.getDate() - 15);
			const newDate2 = new Date(titleExpireDate);
			newDate2.setDate(newDate.getDate() - 15);
			if ( insuranceExpireDate >= today && insuranceExpireDate < futureDate) {
				if (!allVehiclesCalendarEvent.find(item => item.event_reminder_type === 'insurance_expire' && item.target_uuid === vehicle.id)) {
					const calendarEvent = new CalendarEvent({
						title: `Vehicle ${vehicle?.vehicle_number} (${vehicle?.tag})'s Insurance would expire in 15 days`,
						description: `Vehicle ${vehicle?.vehicle_number} (${vehicle?.tag})'s Insurance would expire in 15 day, please check whether it is renewed properly`,
						type: 'reminder',
						start_time: newDate,
						stop_time: new Date(newDate.getTime() + 10*60*1000),
						color: 'brown',
						target_type: 'vehicle',
						target_uuid: vehicle.id,
						target_name: vechile.vehicle_number,
						event_reminder_type: 'insurance_expire',
						status: 'active',
						site: getSite(),
						edit_date: new Date(),
						create_date: new Date(),
						create_by: 'system',
						edit_by: 'system',
						edit_history: [{employee: 'system', date: new Date()}]
					})
					await calendarEvent.save(calendarEvent);
				}
			}
			if ( emissionTestExpireDate >= today && emissionTestExpireDate < futureDate) {
				if (!allVehiclesCalendarEvent.find(item => item.event_reminder_type === 'emission_test' && item.target_uuid === vehicle.id)) {
					const calendarEvent = new CalendarEvent({
						title: `Vehicle ${vehicle?.vehicle_number} (${vehicle?.tag})'s Emission Test would expire in 15 days`,
						description: `Vehicle ${vehicle?.vehicle_number} (${vehicle?.tag})'s Emission Test would expire in 15 day, please check whether it is renewed properly`,
						type: 'reminder',
						start_time: newDate1,
						stop_time: new Date(newDate1.getTime() + 10*60*1000),
						color: 'brown',
						target_type: 'vehicle',
						target_uuid: vehicle.id,
						target_name: vechile.vehicle_number,
						event_reminder_type: 'emission_test',
						status: 'active',
						site: getSite(),
						edit_date: new Date(),
						create_date: new Date(),
						create_by: 'system',
						edit_by: 'system',
						edit_history: [{employee: 'system', date: new Date()}]
					})
					await calendarEvent.save(calendarEvent);
				}
			}
			if ( titleExpireDate >= today && titleExpireDate < futureDate) {
				if (!allVehiclesCalendarEvent.find(item => item.event_reminder_type === 'title_expire' && item.target_uuid === vehicle.id)) {
					const calendarEvent = new CalendarEvent({
						title: `Vehicle ${vehicle?.vehicle_number} (${vehicle?.tag})'s Title would expire in 15 days`,
						description: `Vehicle ${vehicle?.vehicle_number} (${vehicle?.tag})'s Title would expire in 15 day, please check whether it is renewed properly`,
						type: 'reminder',
						start_time: newDate2,
						stop_time: new Date(newDate2.getTime() + 10*60*1000),
						color: 'brown',
						target_type: 'vehicle',
						target_uuid: vehicle.id,
						target_name: vechile.vehicle_number,
						event_reminder_type: 'title_expire',
						status: 'active',
						site: getSite(),
						edit_date: new Date(),
						create_date: new Date(),
						create_by: 'system',
						edit_by: 'system',
						edit_history: [{employee: 'system', date: new Date()}]
					})
					await calendarEvent.save(calendarEvent);
				}
			}
		}
	}

  async createCustomerRelatedEvents(daysAhead = 30) {
		const today = new Date();
		const upcomingDates = [];

		// Calculate dates for the next 'daysAhead' days
		for (let i=0; i<=daysAhead; i++) {
			const targetDate = new Date(today);
			targetDate.setDate(today.getDate() + i);

			upcomingDates.push(targetDate)
		}

		const allCustomers = await Customer.find({ site: getSite()});
		console.log('allCustomers', allCustomers);
		const allExistingBirthdayReminders = await CalendarEvent.find({ type: 'reminder', status: 'active', rrule: 'FREQ=YEARLY', event_reminder_type: 'birthday', site: getSite() });
		const allExistingPaymentReminders = await CalendarEvent.find({ type: 'reminder', status: 'active',  event_reminder_type: 'payment', site: getSite() });

		for (const customer of allCustomers) {
			const [month, day, year] = customer?.birth_date?.split('/').map(Number) || [-1, -1, -1];
			const [month1, day1, year1] = customer?.payment_due_date?.split('/').map(Number) || [-1, -1, -1];
			for (const targetDate of upcomingDates) {
				if (month === targetDate.getMonth() + 1 && day === targetDate.getDate()) {
					console.log('targetDate found', targetDate);
					console.log('are you sure you find', allExistingBirthdayReminders.find((reminder) => reminder.target_uuid === customer?.id));
					if (!allExistingBirthdayReminders.find((reminder) => reminder.target_uuid === customer?.id)) {
						console.log(123123);
						const calendarEvent = new CalendarEvent({
							title: `${customer?.name}'s Birthday`,
							description: `Happy Birthday to ${customer?.name}`,
							type: 'reminder',
							start_time: targetDate,
							stop_time: new Date(targetDate.getTime() + 10*60*1000),
							color: 'orange',
							target_type: 'customer',
							target_uuid: customer?.id,
							target_name: customer?.name,
							event_reminder_type: 'birthday',
							rrule: 'FREQ=YEARLY',
							status: 'active',
							site: getSite(),
							edit_date: new Date(),
							create_date: new Date(),
							create_by: 'system',
							edit_by: 'system',
							edit_history: [{employee: 'system', date: new Date()}]
						});
						console.log('start to create', calendarEvent);
						await calendarEvent.save(calendarEvent);
					}
				}
				if (month1 === targetDate.getMonth() + 1 && day1 === targetDate.getDate()) {
					if (!allExistingPaymentReminders.find((reminder) => reminder.target_uuid === customer?.id)) {
						const calendarEvent = new CalendarEvent({
							title: `${customer?.name}'s Payment Due Date`,
							description: `${customer?.name}'s payment would be due on ${customer?.payment_due_date}`,
							type: 'reminder',
							start_time: targetDate,
							stop_time: new Date(targetDate.getTime() + 10*60*1000),
							color: 'red',
							target_type: 'customer',
							target_uuid: customer?.id,
							target_name: customer?.name,
							event_reminder_type: 'payment',
							status: 'active',
							site: getSite(),
							edit_date: new Date(),
							create_date: new Date(),
							create_by: 'system',
							edit_by: 'system',
							edit_history: [{employee: 'system', date: new Date()}]
						})
						await calendarEvent.save(calendarEvent);
					}
				}
			}
		}
	}
}
module.exports = new ReminderService();