package com.nisum.myteam.service.impl;

import com.nisum.myteam.exception.handler.MyTeamException;
import com.nisum.myteam.model.dao.Project;
import com.nisum.myteam.model.dao.Resource;
import com.nisum.myteam.model.dao.ResourceAllocation;
import com.nisum.myteam.repository.ResourceAllocationRepo;
import com.nisum.myteam.service.IProjectService;
import com.nisum.myteam.service.IResourceAllocationService;
import com.nisum.myteam.utils.MyTeamUtils;
import lombok.extern.slf4j.Slf4j;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.List;

@Service
@Slf4j
public class ResourceAllocationService implements IResourceAllocationService {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private ResourceAllocationRepo resourceAllocationRepo;


    @Autowired
    private IProjectService projectService;

    public ResourceAllocation addResourceAllocation(ResourceAllocation resourceAllocation, String loginEmpId) throws MyTeamException {
        return resourceAllocationRepo.save(resourceAllocation);
    }

    public HashMap<String, Object> updateResource(ResourceAllocation resourceAllocReq, String loginEmpId) throws MyTeamException {

        HashMap<String, Object> respMap = new HashMap<>();

        Project project = projectService.getProjectByProjectId(resourceAllocReq.getProjectId());
        if (resourceAllocReq.getBillingEndDate().compareTo(new Date()) > 0) {

        }


        ResourceAllocation resourceAllocationPers = resourceAllocationRepo.save(resourceAllocReq);

        respMap.put("message", "Resource updated successfully");
        respMap.put("resourceObj", resourceAllocationPers);
        return respMap;
    }

    public Resource deleteResource(String empId, String projectId, ObjectId id, String loginEmpId) {
        return null;
    }


    public List<ResourceAllocation> getResourcesSortByProjectStartDate(String employeeId) {
        Query query = prepareQuery(employeeId, MyTeamUtils.PROJECT_START_DATE);
        return mongoTemplate.find(query, ResourceAllocation.class);
    }

    private Query prepareQuery(String employeeId, String dateColumn) {
        Query query = new Query();
        query.addCriteria(Criteria.where(MyTeamUtils.EMPLOYEE_ID).is(employeeId));
        query.limit(MyTeamUtils.ONE);
        query.with(new Sort(Sort.Direction.DESC, dateColumn));
        return query;
    }


}
