import 'package:hl_lieferservice/exceptions.dart';
import 'package:hl_lieferservice/feature/authentication/bloc/auth_state.dart';
import 'package:hl_lieferservice/feature/authentication/exceptions.dart';
import 'package:hl_lieferservice/main.dart';
import 'package:hl_lieferservice/services/erpframe.dart';
import 'package:intl/intl.dart';

import 'model/delivery.dart';

dynamic getValueOrThrowIfNotPresent(String key, Map<String, dynamic> json) {
  if (!json.containsKey(key)) {
    throw Exception("Wert '$key' in der Konfigurationsdatei nicht gefunden");
  }

  return json[key];
}

/// Returns the current date as string in format YYYY-MM-DD.
String getTodayDate() {
  return DateFormat('yyyy-MM-dd').format(DateTime.now());
}

String concatenateRegexMatches(String input, String pattern) {
  final regex = RegExp(pattern);
  final matches = regex.allMatches(input);

  return matches.fold("", (acc, match) => acc + match[0]!);
}

/// Return the value or the default value if the string is empty.
String getOrDefaultValueFromStr(String value, String defaultValue) {
  if (value != "") {
    return value;
  } else {
    return defaultValue;
  }
}

DeliveryState getDeliveryStateFromString(String str) {
  switch (str) {
    case "laufend":
      return DeliveryState.ongoing;
    case "abgebrochen":
      return DeliveryState.canceled;
    case "vertagt":
      return DeliveryState.onhold;
    case "geliefert":
      return DeliveryState.finished;
    default:
      throw Exception("Invalid state");
  }
}

String getName(DeliveryState state) {
  switch (state) {
    case DeliveryState.ongoing:
      return "laufend";
    case DeliveryState.canceled:
      return "abgebrochen";
    case DeliveryState.onhold:
      return "unterbrochen";
    case DeliveryState.finished:
      return "ausgeliefert";
  }
}

Map<String, String> getSessionOrThrow() {
  if  (locator.isRegistered<Authenticated>()) {
    return {"Cookie": "session_id=${locator.get<Authenticated>().sessionId}"};
  } else {
    throw UserUnauthorized();
  }
}

LocalDocuFrameConfiguration getConfig() {
  if (locator.isRegistered<LocalDocuFrameConfiguration>()) {
    return locator.get<LocalDocuFrameConfiguration>();
  } else {
    throw AppConfigNotFound();
  }
}

Uri urlBuilder(String path) {
  LocalDocuFrameConfiguration config = getConfig();
  return Uri.parse("${config.backendUrl}/v1/execute/$path");
}