import 'package:dio/dio.dart';
import 'package:enough_icalendar/enough_icalendar.dart';

import '../bloc/marianum_dates_state.dart';

class MarianumDatesGetEvents {
  static const String url =
      'https://public-cal.marianumlan.de/cal_public/ad4c5da8-7466-9c72-89cb-8b8d9a5cf26c';

  final Dio _dio = Dio(
    BaseOptions(
      connectTimeout: const Duration(seconds: 10),
      receiveTimeout: const Duration(seconds: 30),
    ),
  );

  Future<List<MarianumDate>> run() async {
    final response = await _dio.get<String>(url);
    final body = response.data;
    if (body == null || body.isEmpty) return [];

    final root = VComponent.parse(body);
    final calendar = root is VCalendar ? root : null;
    final source = calendar?.children ?? root.children;

    final events = source
        .whereType<VEvent>()
        .map(_toMarianumDate)
        .whereType<MarianumDate>()
        .toList();
    events.sort((a, b) => a.start.compareTo(b.start));
    return events;
  }

  static MarianumDate? _toMarianumDate(VEvent e) {
    final start = e.start;
    if (start == null) return null;
    final end = e.end ?? start;
    final isAllDay = _isAllDay(start, end);
    return MarianumDate(
      uid: e.uid,
      title: e.summary ?? '',
      description: e.description,
      start: start,
      end: end,
      isAllDay: isAllDay,
    );
  }

  static bool _isAllDay(DateTime start, DateTime end) {
    final startMidnight =
        start.hour == 0 && start.minute == 0 && start.second == 0;
    final endMidnight = end.hour == 0 && end.minute == 0 && end.second == 0;
    return startMidnight &&
        endMidnight &&
        end.difference(start).inHours % 24 == 0;
  }
}
