import React, {useState, useEffect} from 'react'
import ActiveJobs from '../components/MyActiveJobs/ActiveJobs'
import { useLocation, useNavigate } from 'react-router-dom'
import usersService from '../services/UsersService'

function ManageActiveJobs() {

  const ApiCall = new usersService()

  let navigate = useNavigate()
  let {state} = useLocation()

  let [details, setDetails] = useState({}) // to hold state values

  let [activeJobMesList, setActiveJobMesList] = useState({loading: true, error: false, data: []})

  let [activeJobMesListReload, setActiveJobMesListReload] = useState(false)// state to determine when ACTIVE JOB MESSAGE LIST RELOADS/RE-RENDERS

  const getActiveJobMesList = () => { // FUNCTION TO GET ACTIVE JOB MESSAGE LIST
    setActiveJobMesList({loading: true, error: false, data: []})
    let contract = {contract: state.contract}
    ApiCall.activeJobMesList(contract).then((res)=>{
      if(res.status != 200 || res.data.internal_return < 0){
        setActiveJobMesList({loading: false, error: false, data: []})
        return
      }
      setActiveJobMesList({loading: false, error: false, data: res.data.result_list})
    }).catch((error)=>{
      setActiveJobMesList({loading: false, error: true, data: []})
    })
  }

  useEffect(()=>{
    if(!state){
      navigate('/', {replace: true})
      return
    }
    setDetails(state)
    getActiveJobMesList()
  },[activeJobMesListReload])

  return (
    <ActiveJobs details={state} activeJobMesList={activeJobMesList} reloadActiveJobList={setActiveJobMesListReload} />
  )
}

export default ManageActiveJobs