import 'dart:async';
import 'dart:ui';

import 'package:device_calendar/device_calendar.dart';

final DeviceCalendarPlugin deviceCalendarPlugin = DeviceCalendarPlugin();

class CalendarUtils {
  static Completer<CalendarUtils> _completer;

  Calendar get writableCalendars => calendars?.firstWhere((c) => !c.isReadOnly);
  List<Calendar> calendars;

  CalendarUtils._(this.calendars);

  static Future<CalendarUtils> getInstance() async {
    if (_completer == null) {
      _completer = Completer<CalendarUtils>();
      try {
        final calendarsResult = await deviceCalendarPlugin.retrieveCalendars();
        _completer.complete(CalendarUtils._(calendarsResult?.data));
      } on Exception catch (e) {
        _completer.completeError(e);
        final Future<CalendarUtils> sharedPrefsFuture = _completer.future;
        _completer = null;
        return sharedPrefsFuture;
      }
    }
    return _completer.future;
  }

  Future createOrUpdateEvents({List<DateTime> scheduleList, String title, String description, List<DateTime> scheduleDateTime, List<DayOfWeek> daysOfWeek}) async {
    List<Event> events = List();
    scheduleDateTime.forEach((element) {
      RecurrenceRule recurrenceRule = RecurrenceRule(
        RecurrenceFrequency.Daily,
        daysOfWeek: daysOfWeek,
        endDate: element,
      );
      Event event = Event(writableCalendars.id, recurrenceRule: recurrenceRule, start: element, end: element.add(Duration(minutes: 30)), title: title, description: description);
      events.add(event);
    });

    events.forEach((element) {
      deviceCalendarPlugin.createOrUpdateEvent(element);
    });
  }

  Future createOrUpdateEvent({String title, String description, DateTime scheduleDateTime, String eventId}) async {
    RecurrenceRule recurrenceRule = RecurrenceRule(
      RecurrenceFrequency.Daily,
      // daysOfWeek: daysOfWeek,
      endDate: scheduleDateTime,
    );
    print("eventId " + eventId);
    Event event = Event(writableCalendars.id, recurrenceRule: recurrenceRule, start: scheduleDateTime, end: scheduleDateTime.add(Duration(minutes: 30)), title: title, description: description);
    deviceCalendarPlugin.createOrUpdateEvent(event).catchError((e) {
      print("catchError " + e.toString());
    }).whenComplete(() {
      print("whenComplete " + eventId);
    });
  }

  deleteEvent(Calendar _calendar, Event _event) async {
    await deviceCalendarPlugin.deleteEvent(_calendar.id, _event.eventId);
  }

  Future retrieveEvents(
    String calendarId,
    RetrieveEventsParams retrieveEventsParams,
  ) async {
    return await deviceCalendarPlugin.retrieveEvents(calendarId, retrieveEventsParams);
  }

  Future createCalendar(
    String calendarName, {
    Color calendarColor,
    String localAccountName,
  }) async {
    return await deviceCalendarPlugin.createCalendar(calendarName, calendarColor: calendarColor, localAccountName: localAccountName);
  }
}
