import { useEffect, useState } from "react";
import { cacheData, getCachedData } from "../slices/apiDataManager";
import AttendanceRepository from "../repositories/AttendanceRepository";

export const useAttendace =(projectId)=>{

  const [attendance, setAttendance] = useState([]);
  const[loading,setLoading] = useState(false)
  const [error, setError] = useState(null); 

   const fetchData =  () => {
     const Attendance_cache = getCachedData("Attendance");
     if(!Attendance_cache || Attendance_cache.projectId !== projectId){
      
        setLoading(true);
         AttendanceRepository.getAttendance(projectId)
           .then((response) => {
             setAttendance(response.data);
             cacheData("Attendance", { data: response.data, projectId })
           })
           .catch((error) => {
            setLoading(false)
            setError("Failed to fetch data.");
           })
      }  else {
        setAttendance(Attendance_cache.data);
        setLoading(false)
      }
    };


  useEffect(()=>{
    fetchData(projectId);
  },[projectId])

  return {attendance,loading,error}
}




export const useEmployeeAttendacesLog = (id) => {
  const [logs, setLogs] = useState();
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState(null);

   
  const fetchData =  () => {
    const AttendanceLog_cache = getCachedData("AttendanceLogs");
    if(!AttendanceLog_cache || AttendanceLog_cache.id !== id  ){
       setLoading(true)
       AttendanceRepository.getAttendanceLogs(id).then((response)=>{     
        setLogs(response.data)
        cacheData("AttendanceLogs", { data: response.data, id })
        setLoading(false)
        }).catch((error)=>{
          setError("Failed to fetch data.");
          setLoading(false);
        })     
    }else{
     
      setLogs(AttendanceLog_cache.data);
    }
  };

  useEffect(() => {
    if (id) {
      fetchData(); 
    }

  }, [id]);

  return { logs, loading, error };
};