import { useMemo } from 'react';

import { Media, MediaResource } from '@/back-api';
import { useServiceContext } from '@/service/ServiceContext';
import { SessionServiceProps } from '@/service/session';
import { DataStoreType, useDataStore } from '@/utils/data-store';

export type MediaServiceProps = {
  store: DataStoreType<Media>;
};

export const useMediaService = (): MediaServiceProps => {
  const { media } = useServiceContext();
  return media;
};

export const useMediaServiceWrapped = (
  session: SessionServiceProps
): MediaServiceProps => {
  const store = useDataStore<Media>(
    {
      restApiName: 'Media',
      primaryKey: 'id',
      available: session.token !== undefined,
      getsCall: () => {
        return MediaResource.gets({
          restConfig: session.getRestConfig(),
        });
      },
    },
    [session.token]
  );

  return { store };
};

export const useSpecificMedia = (id: number | undefined) => {
  const { store } = useMediaService();
  const dataMedia = useMemo(() => {
    return store.get(id);
  }, [store.data, id]);
  return { isLoading: store.isLoading, dataMedia };
};

