/**
 * 
 */
package com.nisum.mytime.service;

import java.util.ArrayList;
import java.util.HashMap;
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.Domains;
import com.nisum.mytime.model.EmployeeRoles;
import com.nisum.mytime.repository.DomainRepo;

/**
 * @author Vijay
 *
 */
@Service
public class DomainServiceImpl implements DomainService {
	
	List<Domains> domainList = null;
	List<HashMap<Object, Object>> updatedDomainList = null;
	List<HashMap<String, String>> updatedEmployeeList = null;

    @Autowired
    private DomainRepo domainRepo;
    
    @Autowired
	private MongoTemplate mongoTemplate;
   
    @Override
    public Domains addDomain(Domains d) throws MyTimeException{
        return domainRepo.save(d);
    }
    
    @Override
    public List<HashMap<Object, Object>> getAllDomains() throws MyTimeException {
    	Query activeDomainListQuery = new 	Query(Criteria.where("status").is("Y"));
    	List<Domains> domainList = mongoTemplate.find(activeDomainListQuery, Domains.class);
    	updatedDomainList = new ArrayList<>();
		for (Domains domain : domainList) {
			HashMap<Object, Object> domainMap = new HashMap<>();
			domainMap.put("id",domain.getId());
			domainMap.put("domainName",domain.getDomainName());
			domainMap.put("accountName",domain.getAccountName());
			domainMap.put("status",domain.getStatus());

			updatedEmployeeList = new ArrayList<>();
			List<String> employeeIds=domain.getEmployee();
			Query query = new Query(Criteria.where("employeeId").in(employeeIds));
			List<EmployeeRoles> employeeRoles = mongoTemplate.find(query, EmployeeRoles.class);

			for(EmployeeRoles employeesRole : employeeRoles){
				HashMap<String, String> employeeMap = new HashMap<>();	
				employeeMap.put("id",employeesRole.getEmployeeId());
				employeeMap.put("name",employeesRole.getEmployeeName());
				updatedEmployeeList.add(employeeMap);
			}	
			domainMap.put("deliveryManagers",updatedEmployeeList);
			updatedDomainList.add(domainMap);
		}
    	return updatedDomainList;
    }

    @Override
    public WriteResult deleteDomain(String id) throws MyTimeException{
    	Query query = new 	Query(Criteria.where("domainId").is(id));
    	Update update = new Update(); 
    	update.set("status","N");
    	return mongoTemplate.upsert(query, update,Domains.class);
    }
}
