import { useEffect, useMemo, useState } from 'react';

import { Album, AlbumResource } 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 AlbumServiceProps = {
  store: DataStoreType<Album>;
};

export const useAlbumService = (): AlbumServiceProps => {
  const { album } = useServiceContext();
  return album;
};

export const useAlbumServiceWrapped = (
  session: SessionServiceProps
): AlbumServiceProps => {
  const store = useDataStore<Album>(
    {
      restApiName: 'ALBUM',
      primaryKey: 'id',
      available: session.token !== undefined,
      getsCall: () => {
        return AlbumResource.gets({
          restConfig: session.getRestConfig(),
        });
      },
    },
    [session.token]
  );

  return { store };
};

export const useOrderedAlbums = (titleFilter?: string) => {
  const { store } = useAlbumService();
  const dataAlbums = 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, dataAlbums };
};
export const useSpecificAlbum = (id: number | undefined) => {
  const { store } = useAlbumService();
  const dataAlbum = useMemo(() => {
    return store.get(id);
  }, [store.data, id]);
  return { dataAlbum };
};

export const useAlbumOfAnArtist = (idArtist: number | undefined) => {
  const { store } = useAlbumService();
  const dataAlbum = useMemo(() => {
    return store.get(idArtist);
  }, [store.data, idArtist]);
  return { dataAlbum };
};
