package com.nisum.mytime.service;

import java.util.List;

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.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;

import com.mongodb.WriteResult;
import com.nisum.mytime.exception.handler.MyTimeException;
import com.nisum.mytime.model.RoleMappingInfo;
import com.nisum.mytime.repository.RoleMappingInfoRepo;
import com.nisum.mytime.utils.MyTimeUtils;

@Service
public class RoleMappingServiceImpl implements RoleMappingService {

	@Autowired
	private RoleMappingInfoRepo roleMappingInfoRepo;

	@Autowired
	private MongoTemplate mongoTemplate;

	@Override
	public void saveUniqueEmployeeAndRole(List<String> employeeIds, String roleId, String status)
			throws MyTimeException {

		for (String employeeId : employeeIds) {
			RoleMappingInfo roleMappingInfo = roleMappingInfoRepo.findByEmployeeIdAndRoleId(employeeId, roleId);
			if (roleMappingInfo == null) {
				roleMappingInfo = new RoleMappingInfo();
				roleMappingInfo.setEmployeeId(employeeId);
				roleMappingInfo.setRoleId(roleId);
				roleMappingInfo.setIsActive("Y");
			} else if (roleMappingInfo.getIsActive().equalsIgnoreCase("N")) {
				roleMappingInfo.setIsActive("Y");
			}
			roleMappingInfoRepo.save(roleMappingInfo);
		}
	}

	public WriteResult deleteRole(String employeeId, String roleId) throws MyTimeException {
		Query query = new Query(Criteria.where("employeeId").is(employeeId).and("roleId").is(roleId));
		Update update = new Update();
		update.set(MyTimeUtils.IS_ACTIVE, "N");
		return mongoTemplate.upsert(query, update, RoleMappingInfo.class);
	}

}
