package com.samsung.embo.api.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

import org.springframework.core.env.Environment;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.reactive.function.client.WebClient;
import org.springframework.web.util.UriComponents;
import org.springframework.web.util.UriComponentsBuilder;

import com.samsung.embo.api.service.GhrpService;
import com.samsung.embo.api.util.GhrpSupport;

@Service
public class GhrpServiceImpl implements GhrpService {

	final Environment environment;

	final WebClient webClient;
	private static final int MAX_RETRIES = 2;

	public GhrpServiceImpl(Environment environment, WebClient webClient) {

		this.environment = environment;
		this.webClient = webClient;
	}

	/**
	 * 조직정보 조회
	 * 
	 * @param
	 * @return
	 */
	@Override
	public ArrayList<Map<String, Object>> ghrpGvXstgOrgclmPasgvCdv() throws Exception {
		
		
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("dateFormat", "yyyyMMdd");
		map.put("timestampFormat", "yyyyMMddHHmmssSSS");
		map.put("sqlType", "");
		map.put("execSql", "");

		ArrayList<Map<String, Object>> result = null;

		// 오류발생 시 2번까지는 재처리 한다.
		for (int i = 0; i <= MAX_RETRIES; i++) {
			try {
				result = this.ghrpGvXstgOrgclmPasgvCdv(map);
				// 성공 시 재처리 시도하지 않음
				break;
			} catch (Exception e) {
				System.out.println(e.getMessage());

				// 재시도 전에 1초동안 텀을 둔다
				Thread.sleep(1000);

				// 마지막 재시도에서도 실패할 경우 로깅처리
				if (i == MAX_RETRIES) {
					System.out.println("GHRP 부서정보 : API 재처리 시도 실패 ");
				}
			}
		}

		return result;
	}

	@SuppressWarnings("unchecked")
	private ArrayList<Map<String, Object>> ghrpGvXstgOrgclmPasgvCdv(Map<String, Object> map) {
		
		//GhrpClient  old
		//public static final String TYPE = "ghrp";
		//public static final String API_GROUP = "ghrp";
		/* 조직정보 */
		//@RestApiClient(value = "/kr/ghrp_gv/ghrp_gv_xstg_orgclm_pasgv_cdv/1.0/GHRP_GV_XSTG_ORGCLM_PASGV_CDV", httpMethod = HttpMethod.POST, resultClass = HashMap.class, resultName ="APIData",
			//	apiGroup = API_GROUP, apiKey = "ghrp.ghrpGvXstgOrgclmPasgvCdv", apiName = "ghrp.ghrpGvXstgOrgclmPasgvCdv", debug = false)
		/* 임직원정보 */
		//@RestApiClient(value = "/kr/ghrp_gv/ghrp_gv_xstg_empclm_pasgv_cdv/1.0/GHRP_GV_XSTG_EMPCLM_PASGV_CDV", httpMethod = HttpMethod.POST, resultClass = HashMap.class, resultName ="APIData",
			//	apiGroup = API_GROUP, apiKey = "ghrp.ghrpGvXstgEmpclmPasgvCdv", apiName = "ghrp.ghrpGvXstgEmpclmPasgvCdv", debug = false)

		// URI 생성
        String functionUrl = environment.getProperty("ghrp.dept-service");
        UriComponents uriComponents = UriComponentsBuilder.newInstance()
        		.scheme(GhrpSupport.DEFAULT_PROTOCOL)
        		.host(GhrpSupport.getHost())
        		.path(functionUrl)
        		.build();
        
        ResponseEntity<Object> responseEntity  = webClient 
                .mutate()
                .build()
                .get()
                .uri(uriComponents.toUri())
                .headers(httpHeaders -> httpHeaders.addAll(GhrpSupport.getHeader(MediaType.APPLICATION_JSON)))
                .retrieve()
                .toEntity(Object.class)
                .block();

        return (ArrayList<Map<String, Object>>) Objects.requireNonNull(responseEntity).getBody();

		
	}

	/**
	 * 인사정보 조회
	 * 
	 * @param
	 * @return
	 */
	@Override
	public ArrayList<Map<String, Object>> ghrpGvXstgEmpclmPasgvCdv() throws Exception {
		/*
		 * Map<String, Object> map = new HashMap<String, Object>();
		 * map.put("dateFormat", "yyyyMMdd"); map.put("timestampFormat",
		 * "yyyyMMddHHmmssSSS"); map.put("sqlType", ""); map.put("execSql", "");
		 */

		 String functionUrl = environment.getProperty("ghrp.emp-service");
	        UriComponents uriComponents = UriComponentsBuilder.newInstance()
	        		.scheme(GhrpSupport.DEFAULT_PROTOCOL)
	        		.host(GhrpSupport.getHost())
	        		.path(functionUrl)
	        		.build();
	        
	        ResponseEntity<Object> responseEntity  = webClient 
	                .mutate()
	                .build()
	                .get()
	                .uri(uriComponents.toUri())
	                .headers(httpHeaders -> httpHeaders.addAll(GhrpSupport.getHeader(MediaType.APPLICATION_JSON)))
	                .retrieve()
	                .toEntity(Object.class)
	                .block();

	        return (ArrayList<Map<String, Object>>) Objects.requireNonNull(responseEntity).getBody();
	}
}
