import { useState, useEffect } from "react";
import { useDispatch, useSelector } from "react-redux";
import {
  getFileProcess,
  getFileProcessOther,
} from "../services/getFileProcess";
import useUserProfile from "../../authentication/hooks/useUserProfile";
import { getRoleFromUrl } from "../../../utils/getRoleFromUrl";

export function getFileFromApi(roles, id, dispatch) {
  if (
    (getRoleFromUrl() === "CityOperator" ||
      getRoleFromUrl() === "Poultry" ||
      getRoleFromUrl() === "KillHouse") &&
    (roles.includes("Poultry") ||
      roles.includes("CityOperator") ||
      roles.includes("KillHouse"))
  ) {
    dispatch(getFileProcessOther(id));
  } else {
    dispatch(getFileProcess(id));
  }
}

const useRequestFile = (id) => {
  const dispatch = useDispatch();
  const file = useSelector((state) => state.fileSlice);
  const [data, setData] = useState(file);
  const [roles] = useUserProfile();

  useEffect(() => {
    if (
      (getRoleFromUrl() === "CityOperator" ||
        getRoleFromUrl() === "Poultry" ||
        getRoleFromUrl() === "KillHouse" ||
        getRoleFromUrl() === "KillHouseVet") &&
      (roles.includes("Poultry") ||
        roles.includes("CityOperator") ||
        roles.includes("KillHouse") ||
        roles.includes("KillHouseVet"))
    ) {
      dispatch(getFileProcessOther(id));
    } else {
      dispatch(getFileProcess(id));
    }
  }, []);

  useEffect(() => {
    setData(file);
  }, [file]);

  return data ? data : [];
};

export default useRequestFile;
