import { Injectable } from '@nestjs/common';
import { google } from 'googleapis';
import { FilterGoogleCalendarEntity } from '../../entities/filter-google-calendar.entity';

@Injectable()
export class IndexHolidayCalendarManager {
  async execute(param: FilterGoogleCalendarEntity) {
    const events = [];
    const calendar = google.calendar({
      version: 'v3',
      auth: process.env.GOOGLE_CALENDAR_KEY,
    });
    const calendarId = 'id.indonesian#holiday@group.v.calendar.google.com';

    const res = await calendar.events.list({
      calendarId: calendarId,
      timeMin: param.start_date
        ? param.start_date + 'T00:00:00Z'
        : new Date().getFullYear() + '-01-01T00:00:00Z',
      timeMax: param.end_date
        ? param.end_date + 'T23:59:59Z'
        : new Date().getFullYear() + '-12-31T23:59:59Z',
      singleEvents: true,
      orderBy: 'startTime',
    });

    res.data.items?.forEach((item) => {
      //   const eventName = item.summary.replace("Joint", "").replace("for", "").replace("after", "").replace("Holiday","").trim();
      let eventName = item.summary.replace('Cuti Bersama', '').trim();

      // function ini untuk menyamakan dan menggabungkan Hari Libur
      if (eventName == 'Hari Idul Fitri')
        eventName = eventName.replace('Hari', '').trim();
      else if (eventName == 'Natal (Hari Tinju)' || eventName == 'Malam Natal')
        eventName = 'Hari Raya Natal';

      const exist = events.find((event) => {
        return event.holiday_name
          .toLowerCase()
          .includes(eventName.toLowerCase());
      });

      if (exist) {
        Object.assign(exist, {
          end_date: item.start.date,
          total_day: exist.total_day + 1,
        });
      } else {
        events.push({
          holiday_name: eventName,
          start_date: item.start?.date,
          end_date: item.start?.date,
          total_day: 1,
        });
      }
    });

    return events;
  }
}
