<script>
import {ref} from 'vue';

// Define reactive properties
const id = ref(null);
const icsUrl = ref(null);
const events = ref([]);
const customFunctions = ref({});
const eventClick = ref(null);

/** Random ID generator */
const generateRandomId = () => {
  return Math.floor(Math.random() * 1000000);
};

/** Default objects -> Event */
const defaultEvent = {
  id: null,
  title: '',
  start: '',
  end: '',
  allDay: false,
};

/** Default objects -> Calendar */
const defaultCalendar = {
  id: 'calendar',
  events: [],
  eventClick: null,
};

/** Functions -> Event click */
const functions_eventClick = {
  setEventClick: (callback) => {
    eventClick.value = callback;
  },
  getEventClick: () => {
    return eventClick.value;
  },
  clearEventClick: () => {
    eventClick.value = null;
  },
  executeEventClick: (event) => {
    if (eventClick.value) {
      console.log('Event clicked:', event, 'ID: ', event.event.id);
      eventClick.value(event);
    } else {
      console.warn('No event click function set');
    }
  },
};

/** Functions -> ID management */
const functions_id = {
  getId: () => {
    return id.value;
  },
  setId: (newId) => {
    id.value = newId;
  },
  generateId: () => {
    id.value = generateRandomId();
  },
  generateRandomId,
};

/** Functions -> Event management */
const functions_event = {
  generateEventObject: (event) => {
    return {
      ...defaultEvent,
      ...event,
    };
  },
  addEvent: (event) => {
    const newEvent = functions_event.generateEventObject(event);
    events.value.push(newEvent);
  },
  removeEvent: (eventId) => {
    events.value = events.value.filter(event => event.id !== eventId);
  },
  updateEvent: (eventId, updatedEvent) => {
    const eventIndex = events.value.findIndex(event => event.id === eventId);
    if (eventIndex !== -1) {
      events.value[eventIndex] = {
        ...events.value[eventIndex],
        ...updatedEvent,
      };
    }
  },
  getEvents: () => {
    return events.value;
  },
  clearEvents: () => {
    events.value = [];
  },
};

/** Functions -> ICS management */
const functions_ics = {
  setIcsUrl: (url) => {
    // Set the ICS URL
    icsUrl.value = url;
  },
  getIcsUrl: () => {
    // Get the ICS URL
    return icsUrl.value;
  },
  clearIcsUrl: () => {
    // Clear the ICS URL
    icsUrl.value = null;
  },
  fetchIcsData: async () => {
    // Fetch the ICS data from the URL
    if (icsUrl.value) {
      try {
        const response = await fetch(icsUrl.value);
        if (!response.ok) {
          throw new Error('Network response was not ok');
        }
        return await response.text();
      } catch (error) {
        console.error('Error fetching ICS data:', error);
      }
    } else {
      console.warn('No ICS URL set');
    }
  },
  parseIcsData: (data) => {
    // Parse the ICS data and return events
    const events = [];
    const lines = data.split('\n');
    let event = {};
    lines.forEach(line => {
      if (line.startsWith('BEGIN:VEVENT')) {
        event = {};
      } else if (line.startsWith('END:VEVENT')) {
        events.push(event);
      } else {
        const [key, value] = line.split(':');
        if (key && value) {
          event[key.trim()] = value.trim();
        }
      }
    });
    return events;
  },
  fetchAndParseIcsData: async () => {
    // Fetch and parse the ICS data
    const data = await functions_ics.fetchIcsData();
    if (data) {
      return functions_ics.parseIcsData(data);
    }
    return [];
  },
};

/** Functions -> Custom functions */
const functions_custom = {
  addCustomFunction: (name, func) => {
    customFunctions.value[name] = func;
  },
  removeCustomFunction: (name) => {
    delete customFunctions.value[name];
  },
  executeCustomFunction: (name, ...args) => {
    if (customFunctions.value[name]) {
      return customFunctions.value[name](...args);
    } else {
      console.warn(`Custom function ${name} not found`);
    }
  },
  getCustomFunction: (name) => {
    return customFunctions.value[name];
  },
  getAllCustomFunctions: () => {
    return customFunctions.value;
  },
  clearCustomFunctions: () => {
    customFunctions.value = {};
  },
};

// Define the functions
const functions_default = {
  ...functions_id,
  ...functions_event,
  ...functions_ics,
  ...functions_custom,
};

// Define the functions to be used in the component
const functions = {
  ...functions_default,
  ...customFunctions,
};


// Define the calendar object
const calendar = {
  id: 'calendar',
  functions,
  eventClick: functions_eventClick,
};


// Export all functions and properties
export {
  calendar,
};
</script>