package com.nisum.myteam.service.impl;

import com.nisum.myteam.model.dao.EmployeeSubStatus;
import com.nisum.myteam.repository.EmployeeSubStatusRepo;
import com.nisum.myteam.service.ISubStatusService;
import com.nisum.myteam.utils.MyTeamDateUtils;
import com.nisum.myteam.utils.MyTeamUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class SubStatusService implements ISubStatusService {

    @Autowired
    private EmployeeSubStatusRepo employeeSubStatusRepo;


    @Override
    public EmployeeSubStatus getLatestEmployeeSubStatus(String empId) {
        List<EmployeeSubStatus> employeeSubStatusList = employeeSubStatusRepo.findByEmployeeID(empId);
        EmployeeSubStatus latestSubStatus = null;
        if(!employeeSubStatusList.isEmpty()){
            latestSubStatus = employeeSubStatusList.get(0);
            for(EmployeeSubStatus s:employeeSubStatusList) {
                if(s.getToDate().after(latestSubStatus.getToDate())){
                    latestSubStatus = s;
                }
            }
        }
        return latestSubStatus;
    }


    @Override
    public EmployeeSubStatus updateExistingEmplyeeSubStatus(EmployeeSubStatus employeeSubStatusReq) {
        employeeSubStatusReq.setFromDate(MyTeamDateUtils.getDayMoreThanDate(employeeSubStatusReq.getFromDate()));
        employeeSubStatusReq.setToDate(MyTeamDateUtils.getDayMoreThanDate(employeeSubStatusReq.getToDate()));
        return employeeSubStatusRepo.save(employeeSubStatusReq);
    }

    @Override
    public EmployeeSubStatus addEmployeeSubStatus(EmployeeSubStatus employeeSubStatus) {
        employeeSubStatus.setFromDate(MyTeamDateUtils.getDayMoreThanDate(employeeSubStatus.getFromDate()));
        employeeSubStatus.setToDate(MyTeamDateUtils.getDayMoreThanDate(employeeSubStatus.getToDate()));
        return employeeSubStatusRepo.insert(employeeSubStatus);
    }

    @Override
    public EmployeeSubStatus getCurrentSubStatus(String employeeId){
        List<EmployeeSubStatus> currentEmployeeSubStatusList = employeeSubStatusRepo.findByEmployeeID(employeeId).stream().filter(
                s -> s.getFromDate().compareTo(new Date())<=0 && s.getToDate().compareTo(new Date())>=0).collect(Collectors.toList());
        if(!currentEmployeeSubStatusList.isEmpty()){
            return currentEmployeeSubStatusList.get(0);
        }else
            return null;
    }

    @Override
    public EmployeeSubStatus endSubStatus(EmployeeSubStatus subStatus){
        EmployeeSubStatus currentSubStatus = getCurrentSubStatus(subStatus.getEmployeeID());
        if(currentSubStatus!=null){
            currentSubStatus.setToDate(MyTeamDateUtils.getDayLessThanDate(new Date()));
            updateExistingEmplyeeSubStatus(currentSubStatus);
        }
        return null;
    }

}
