package com.nisum.myteam.service.impl;

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

import org.springframework.beans.factory.annotation.Autowired;
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 com.nisum.myteam.model.Billing;
import com.nisum.myteam.model.Employee;
import com.nisum.myteam.repository.BillingRepo;
import com.nisum.myteam.service.IBillingService;
import com.nisum.myteam.utils.MyTeamUtils;

import lombok.extern.slf4j.Slf4j;

@Service
@Slf4j
public class BillingService implements IBillingService {

	@Autowired
	private BillingRepo billingRepo;

	@Autowired
	private MongoTemplate mongoTemplate;

	@Override
	public Billing addBilling(Billing billing, String loginEmpId) {
		billing.setAuditFields(loginEmpId, MyTeamUtils.CREATE);
		return billingRepo.save(billing);
	}

	@Override
	public Billing updateBilling(Billing billing, String loginEmpId) {
		billing.setAuditFields(loginEmpId, MyTeamUtils.UPDATE);
		return billingRepo.save(billing);
	}

	@Override
	public void deleteBilling(Billing billing) {
		billingRepo.delete(billing);
	}

	@Override
	public List<Billing> getBillingsForProject(String empId, String projectId) {
		List<Billing> billingsList = billingRepo.findByEmployeeIdAndProjectId(empId, projectId);

		if (billingsList == null || billingsList.size() == 0) {
			return billingsList;
		} else {
			return billingsList.stream().sorted(Comparator.comparing(Billing::getCreatedOn).reversed())
					.collect(Collectors.toList());
		}

	}

	@Override
	public List<Billing> getBillingsForEmployee(String empId) {
		List<Billing> billingsList = billingRepo.findByEmployeeId(empId);
		if (billingsList == null || billingsList.size() == 0) {
			return billingsList;
		} else {
			return billingsList.stream().sorted(Comparator.comparing(Billing::getCreatedOn).reversed())
					.collect(Collectors.toList());
		}
	}

	@Override
	public List<Billing> getActiveBillings(String empId, String projectId) {
		Query query = new Query();
		query.addCriteria(Criteria.where("active").is(new Boolean(true)));
		query.addCriteria(Criteria.where("employeeId").is(empId));
		query.addCriteria(Criteria.where("projectId").is(projectId));

		List<Billing> billingList = mongoTemplate.find(query, Billing.class);

		if (billingList == null || billingList.size() == 0) {
			return billingList;
		} else {
			return billingList.stream().sorted(Comparator.comparing(Billing::getBillingStartDate).reversed())
					.collect(Collectors.toList());
		}

	}

	public Billing addBillingtoResource(Billing billing, Employee employee, String loginEmpId) {

		billing.setBillingEndDate(employee.getEndDate());
		billing.setActive(false);
		billing.setAuditFields(loginEmpId, MyTeamUtils.UPDATE);
		return billingRepo.save(billing);
	}

}
