import { useMemo } from 'react';

import { Gender, GenderResource } from '@/back-api';
import { useServiceContext } from '@/service/ServiceContext';
import { SessionServiceProps } from '@/service/session';
import { DataStoreType, useDataStore } from '@/utils/data-store';
import { DataTools, TypeCheck } from '@/utils/data-tools';
import { isNullOrUndefined } from '@/utils/validator';

export type GenderServiceProps = {
  store: DataStoreType<Gender>;
};

export const useGenderService = (): GenderServiceProps => {
  const { gender } = useServiceContext();
  return gender;
};

export const useGenderServiceWrapped = (
  session: SessionServiceProps
): GenderServiceProps => {
  const store = useDataStore<Gender>(
    {
      restApiName: 'GENDER',
      primaryKey: 'id',
      available: session.token !== undefined,
      getsCall: () => {
        return GenderResource.gets({
          restConfig: session.getRestConfig(),
        });
      },
    },
    [session.token]
  );

  return { store };
};

export const useOrderedGenders = (titleFilter?: string) => {
  const { store } = useGenderService();
  const dataGenders = useMemo(() => {
    let tmpData = store.data;
    if (!isNullOrUndefined(titleFilter)) {
      tmpData = DataTools.getNameLike(tmpData, titleFilter);
    }
    return DataTools.getsWhere(
      tmpData,
      [
        {
          check: TypeCheck.NOT_EQUAL,
          key: 'id',
          value: [undefined, null],
        },
      ],
      ['name', 'id']
    );
  }, [store.data, titleFilter]);
  return { isLoading: store.isLoading, dataGenders };
};
export const useSpecificGender = (id: number | undefined) => {
  const { store } = useGenderService();
  const dataGender = useMemo(() => {
    return store.get(id);
  }, [store.data, id]);
  return { dataGender };
};

export const useGenderOfAnArtist = (idArtist: number | undefined) => {
  const { store } = useGenderService();
  const dataGender = useMemo(() => {
    return store.get(idArtist);
  }, [store.data, idArtist]);
  return { dataGender };
};
