DateTime weekStartFor(DateTime date) {
  return date.subtract(Duration(days: date.weekday % 7));
}

bool isSameDay(DateTime a, DateTime b) {
  return a.year == b.year && a.month == b.month && a.day == b.day;
}

bool shouldShowCurrentMarker(DateTime selectedDate, DateTime now) {
  return isSameDay(selectedDate, now);
}

String formatHm(DateTime dateTime) {
  final hour = dateTime.hour.toString().padLeft(2, '0');
  final minute = dateTime.minute.toString().padLeft(2, '0');
  return '$hour:$minute';
}

String formatHour(int hour) {
  if (hour == 24) {
    return '00:00';
  }
  return '${hour.toString().padLeft(2, '0')}:00';
}

DateTime? parseYmd(String? ymd) {
  if (ymd == null) {
    return null;
  }
  final matched = RegExp(r'^(\d{4})-(\d{2})-(\d{2})$').firstMatch(ymd);
  if (matched == null) {
    return null;
  }
  final year = int.parse(matched.group(1)!);
  final month = int.parse(matched.group(2)!);
  final day = int.parse(matched.group(3)!);
  final parsed = DateTime(year, month, day);
  if (parsed.year != year || parsed.month != month || parsed.day != day) {
    return null;
  }
  return parsed;
}

String formatYmd(DateTime dateTime) {
  final year = dateTime.year.toString().padLeft(4, '0');
  final month = dateTime.month.toString().padLeft(2, '0');
  final day = dateTime.day.toString().padLeft(2, '0');
  return '$year-$month-$day';
}

List<DateTime> monthDatesFor(DateTime date) {
  final monthStart = DateTime(date.year, date.month, 1);
  final monthEnd = DateTime(date.year, date.month + 1, 0);
  return List.generate(
    monthEnd.day,
    (index) => DateTime(monthStart.year, monthStart.month, index + 1),
  );
}
