import { useMemo } from 'react';

import { Season, SeasonResource } 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';
import { useMediaService } from './Media';

export type SeasonServiceProps = {
  store: DataStoreType<Season>;
};

export const useSeasonService = (): SeasonServiceProps => {
  const { season } = useServiceContext();
  return season;
};

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

  return { store };
};

export const useOrderedSeasons = (titleFilter?: string) => {
  const { store } = useSeasonService();
  const dataSeasons = 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, dataSeasons };
};
export const useSpecificSeason = (id: number | undefined) => {
  const { store } = useSeasonService();
  const dataSeason = useMemo(() => {
    return store.get(id);
  }, [store.data, id]);
  return { dataSeason };
};


export const useSeasonVideo = (id?: number) => {
  const { store } = useSeasonService();
  const seasonVideo = useMemo(() => {
    if (id === undefined) {
      return [];
    }
    return DataTools.getsWhere(
      store.data,
      [
        {
          check: TypeCheck.EQUAL,
          key: 'seasonId',
          value: id,
        },
      ],
      ['episode', 'name']
    );
  }, [store.data, id]);
  return { isLoading: store.isLoading, seasonVideo };
};

export const useSeasonCountVideo = (seasonId?: number) => {
  const { store } = useMediaService();
  const seasonCountVideo = useMemo(() => {
    if (seasonId === undefined) {
      return 0;
    }
    return DataTools.count(
      store.data,
      [
        {
          check: TypeCheck.EQUAL,
          key: 'seasonId',
          value: seasonId,
        },
      ]
    );
  }, [store.data, seasonId]);
  return { isLoading: store.isLoading, seasonCountVideo };
};
