import { ref } from "vue";
import { ValidationExceptionInterface } from "ChillMainAssets/types";

export function useViolationList<
  T extends Record<string, Record<string, string>>,
>() {
  type ViolationKey = Extract<keyof T, string>;
  const violationsList = ref<ValidationExceptionInterface<T> | null>(null);

  function violationTitles<P extends ViolationKey>(property: P): string[] {
    if (null === violationsList.value) {
      return [];
    }
    const r = violationsList.value
      .violationsByNormalizedProperty(property)
      .map((v) => v.title);

    return r;
  }
  function violationTitlesWithParameter<
    P extends ViolationKey,
    Param extends Extract<keyof T[P], string>,
  >(
    property: P,
    with_parameter: Param,
    with_parameter_value: T[P][Param],
  ): string[] {
    if (violationsList.value === null) {
      return [];
    }
    return violationsList.value
      .violationsByNormalizedPropertyAndParams(
        property,
        with_parameter,
        with_parameter_value,
      )
      .map((v) => v.title);
  }

  function hasViolation<P extends ViolationKey>(property: P): boolean {
    return violationTitles(property).length > 0;
  }
  function hasViolationWithParameter<
    P extends ViolationKey,
    Param extends Extract<keyof T[P], string>,
  >(
    property: P,
    with_parameter: Param,
    with_parameter_value: T[P][Param],
  ): boolean {
    return (
      violationTitlesWithParameter(
        property,
        with_parameter,
        with_parameter_value,
      ).length > 0
    );
  }

  function setValidationException<V extends ValidationExceptionInterface<T>>(
    validationException: V,
  ): void {
    violationsList.value = validationException;
  }

  function cleanException(): void {
    violationsList.value = null;
  }

  return {
    violationTitles,
    violationTitlesWithParameter,
    setValidationException,
    cleanException,
    hasViolationWithParameter,
    hasViolation,
  };
}
