import { useMemo } from 'react';

import { Artist, ArtistResource } 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 ArtistServiceProps = {
  store: DataStoreType<Artist>;
};

export const useArtistService = (): ArtistServiceProps => {
  const { artist } = useServiceContext();
  return artist;
};

export const useArtistServiceWrapped = (
  session: SessionServiceProps
): ArtistServiceProps => {
  const store = useDataStore<Artist>(
    {
      restApiName: 'ARTIST',
      primaryKey: 'id',
      available: session.token !== undefined,
      getsCall: () => {
        return ArtistResource.gets({
          restConfig: session.getRestConfig(),
        });
      },
    },
    [session.token]
  );

  return { store };
};

export const useOrderedArtists = (nameFilter?: string) => {
  const { store } = useArtistService();
  const dataArtist = useMemo(() => {
    let tmpData = store.data;
    if (!isNullOrUndefined(nameFilter)) {
      tmpData = DataTools.getNameLike(tmpData, nameFilter);
    }
    return DataTools.getsWhere(
      tmpData,
      [
        {
          check: TypeCheck.NOT_EQUAL,
          key: 'id',
          value: [undefined, null],
        },
      ],
      ['name', 'id']
    );
  }, [store.data, nameFilter]);
  return { isLoading: store.isLoading, dataArtist };
};

export const useSpecificArtist = (id: number | undefined) => {
  const { store } = useArtistService();
  const dataArtist = useMemo(() => {
    return store.get(id);
  }, [store.data, id]);
  return { dataArtist };
};

export const useSpecificArtists = (ids: number[] | undefined) => {
  const { store } = useArtistService();
  const dataArtists = useMemo(() => {
    return store.gets(ids);
  }, [store.data, ids]);
  return { dataArtists };
};
