import { useCallback } from "react";
import useHttpRequest from "../../../hooks/useHttpRequest";
import { get, del } from "../../../utils/axios";
import { defaultResourcesFilters } from "../../../constants/resourcesConstants";

const cdn = process.env.REACT_APP_CDN_URL;

const getResourcesEndpoint = (filters) => {
  const {
    page,
    pageSize,
    sortBy,
    sortDirection,
    fullTextSearch,
    resourceCode,
    resourceName,
    categoryId,
    secured
  } = filters;
  let endpoint = `${cdn}/admin/resources?Page=${page}&PageSize=${pageSize}`;
  if (sortBy) endpoint += `&SortBy=${sortBy}`;
  if (sortDirection) endpoint += `&SortDirection=${sortDirection}`;
  if (fullTextSearch) endpoint += `&FullTextSearch=${fullTextSearch}`;
  if (resourceCode) endpoint += `&ResourceCode=${resourceCode}`;
  if (resourceName) endpoint += `&ResourceName=${resourceName}`;
  if (categoryId) endpoint += `&CategoryId=${categoryId}`;
  if (secured) endpoint += `&Secured=${secured}`;
  return endpoint;
};

const useResourcesApi = () => {
  const { exec } = useHttpRequest();

  const getResources = useCallback(
    (filters, options) => {
      const input = { ...defaultResourcesFilters, ...filters };
      const endpoint = getResourcesEndpoint(input);
      const promise = exec(() => get(endpoint), options);
      return promise;
    },
    [exec]
  );

  const getResource = useCallback(
    (resourceId, options) => {
      const endpoint = `${cdn}/admin/resource?ResourceId=${resourceId}`;
      const promise = exec(() => get(endpoint), options);
      return promise;
    },
    [exec]
  );

  const deleteResource = useCallback(
    (resourceId, options) => {
      const endpoint = `${cdn}/admin/resource?ResourceId=${resourceId}`;
      const promise = exec(() => del(endpoint), options);
      return promise;
    },
    [exec]
  );

  return {
    getResources,
    getResource,
    deleteResource
  };
};

export default useResourcesApi;
