import { ANNAN_KAND_ORSAK_ID } from '@msfa-constants/franvaro-reasons';
import { OrsaksKoderFranvaro } from '@msfa-enums/orsaks-koder-franvaro.enum';
import { OrsaksKoderKanda } from '@msfa-enums/orsaks-koder-kanda.enum';
import { FranvaroReasonResponse } from './api/franvaro-reason.response.model';

export interface FranvaroReason {
  name: string;
  value: number;
  position?: number;
}

export function mapResponseToFranvaroReason(data: FranvaroReasonResponse): FranvaroReason {
  const { name, id } = data;

  return {
    name,
    value: id,
  };
}

export function sortFranvaroReasons(reasons: FranvaroReason[]): FranvaroReason[] {
  const filteredReasons = reasons.filter(reason =>
    reason.value !== OrsaksKoderFranvaro.ANNAN_KÄND_ORSAK);

  for (const reason of filteredReasons) {
    switch (reason.value) {
      case OrsaksKoderFranvaro.SJUK:
        reason.position = 1;
        break;
      case OrsaksKoderFranvaro.ARBETE:
        reason.position = 3;
        break;
      case OrsaksKoderFranvaro.OKÄND_ORSAK:
        reason.position = 10;
        break;
      case OrsaksKoderFranvaro.VAB:
        reason.position = 2;
        break;
      case OrsaksKoderFranvaro.UTBILDNING:
        reason.position = 4;
        break;
      case OrsaksKoderKanda.LakarbesokTandlakarbesok:
        reason.position = 6;
        break;
      case OrsaksKoderKanda.Familjeangelagenhet:
        reason.position = 8;
        break;
      case OrsaksKoderKanda.MoteMedMyndighet:
        reason.position = 7;
        break;
      case OrsaksKoderKanda.Anstallningsintervju:
        reason.position = 5;
        break;
      case OrsaksKoderKanda.AnnanOrsak:
        reason.position = 9;
        break;
      default:
        break;
    }
  }

  return filteredReasons.sort((reasonA, reasonB) => reasonA.position - reasonB.position);
}

export function setKnownReason(knownReason: string): string {
  let reason: string;

  for (const orsakskod in OrsaksKoderFranvaro) {
    if (orsakskod === knownReason) {
      return reason = knownReason;
    } else {
      reason = ANNAN_KAND_ORSAK_ID;
    }
  }

  return reason;
}
