package org.fouram.service;

import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.fouram.core.base.service.BaseService;
import org.fouram.core.base.service.RequestService;
import org.fouram.core.util.JsonNodeUtil;
import org.fouram.entity.SapUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.fasterxml.jackson.databind.JsonNode;
import com.google.common.collect.Maps;

@Service
public class SapEmpJobService extends BaseService {

	@Autowired
	private RequestService requestService;

	public void setPosition(List<SapUser> sapUsers) {
		String url = "https://api15.sapsf.cn/odata/v2/EmpJob?$filter=userId in %s&$format=json";
		url = String.format(url, getUserIds(sapUsers));
		JsonNode node = requestService.getForObject(url, getHttpHeaders());
		Map<String, String> jobTitleMap = Maps.newHashMap();
		if (node != null) {
			Iterator<JsonNode> iterator = node.get("d").get("results").elements();
			while (iterator.hasNext()) {
				JsonNode userNode = iterator.next();
				String userId = JsonNodeUtil.getValue(userNode, "userId");
				String jobTitle = JsonNodeUtil.getValue(userNode, "jobTitle");
				jobTitleMap.put(userId, jobTitle);
			}
		}
		for(SapUser sapUser : sapUsers) {
			sapUser.setPosition(jobTitleMap.get(sapUser.getUserId()));
			sapUser.setFormatPosition(formatPosition(sapUser.getPosition()));
		}
	}
}
