package com.bb.api;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import jakarta.servlet.http.HttpServletRequest;

import org.codehaus.jettison.json.JSONArray;
import org.codehaus.jettison.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.bb.jwt.JwtManager;
import com.bb.model.ApiResponse;
import com.bb.model.CmnSearch;
import com.bb.model.Site;
import com.bb.model.SiteVendorSkinVO;
import com.bb.service.BetRadarService;
import com.bb.service.SettingService;
import com.bb.service.SiteService;
import com.bb.util.IPKit;
import com.fasterxml.jackson.databind.ObjectMapper;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@Controller
@RequiredArgsConstructor
@RequestMapping(value = "/api/v1/setting")
public class ApiSettingController {

	@Autowired
	SiteService siteService;
	
	@Autowired
	SettingService settingService;
	
	@Autowired
	BetRadarService betRadarService;
	
	@Autowired
	private final JwtManager jwtManager;
	
	
	@ResponseBody	
	@PostMapping("/vendor")
    public ApiResponse settingVendorList(@RequestHeader String token, HttpServletRequest request, @RequestBody CmnSearch search) throws Exception {
		ApiResponse apiResponse = new ApiResponse();
		
		try {
			Site site = siteService.getSiteInfoAPI(request);
			if(site == null) {
				apiResponse.setResultCode("9999");
				apiResponse.setResultMessage("Authorization apiKey check");
				return apiResponse;
			}
			
			if( !( site.getSiteIp()==null || "".equals(site.getSiteIp())
					|| "3.3.3.3".equals(site.getSiteIp()) || site.getSiteIp().indexOf(IPKit.getIpAddressByRequest(request)) >= 0) ) {
				log.error("site.getSiteIp("+site.getSiteIp()+"), denied" + IPKit.getIpAddressByRequest(request));
				apiResponse.setResultCode("10001");
				return apiResponse;
			}
			
			// TO DO 토큰체크 
			Map responseData = new HashMap();
			
			try {
				JwtManager.TokenInfo tokenInfo = jwtManager.getTokenInfoAdmin(token);
				final String LOG_PREFIX = "#-API::SETTING::settingVendorList::"+tokenInfo.getSid()+"::::";
				
				// POJO to JSON
				ObjectMapper objectMapper = new ObjectMapper();
				String reqJsonStr = objectMapper.writeValueAsString(search);
				JSONObject reqObj = new JSONObject(reqJsonStr);
				log.info(LOG_PREFIX+ "Request {}", reqObj);
				
				// 여기서 부터 로직
				if(search.getSiteIdx() == null || search.getSiteIdx() == 0) {
					search.setSiteIdx((long) site.getSiteIdx());
					search.setSiteId(tokenInfo.getSid());
				}
		    	log.info(LOG_PREFIX + "CmnSearch::"+search.toString());
		    	
				List<HashMap<String, Object>> list = settingService.getSettingVendorList(search);
				for(HashMap<String, Object> item : list) {
					Long vendorIdx = (Long) item.get("vendorIdx");
					String vendorTitle = item.get("vendorTitle").toString();
					search.setVendorIdx(vendorIdx);
					search.setVendorTitle(vendorTitle);
					List<HashMap<String, Object>> skinList = settingService.getSettingSkinList(search);
					item.put("skinList", skinList);
				}
				responseData.put("list", list);
				
				
			} catch(Exception e) {
				e.printStackTrace();
				log.info(e.toString());
				apiResponse.setResultCode("99995");
				apiResponse.setResultMessage("token is no valid");
				return apiResponse;
			}
			
			apiResponse.setData(responseData);
			apiResponse.success();
			
		} catch (Exception e) {
			e.printStackTrace();
			apiResponse.fail();
		}
		
		return apiResponse;
	}
	
	
	@ResponseBody	
	@PostMapping("/skin")
    public ApiResponse settingSkinList(@RequestHeader String token, HttpServletRequest request, @RequestBody CmnSearch search) throws Exception {
		ApiResponse apiResponse = new ApiResponse();
		
		try {
			Site site = siteService.getSiteInfoAPI(request);
			if(site == null) {
				apiResponse.setResultCode("9999");
				apiResponse.setResultMessage("Authorization apiKey check");
				return apiResponse;
			}
			
			if( !( site.getSiteIp()==null || "".equals(site.getSiteIp())
					|| "3.3.3.3".equals(site.getSiteIp()) || site.getSiteIp().indexOf(IPKit.getIpAddressByRequest(request)) >= 0) ) {
				log.error("site.getSiteIp("+site.getSiteIp()+"), denied" + IPKit.getIpAddressByRequest(request));
				apiResponse.setResultCode("10001");
				return apiResponse;
			}
			
			// TO DO 토큰체크 
			Map responseData = new HashMap();
			
			try {
				JwtManager.TokenInfo tokenInfo = jwtManager.getTokenInfoAdmin(token);
				final String LOG_PREFIX = "#-API::SETTING::settingSkinList::"+tokenInfo.getSid()+"::::";
				
				// POJO to JSON
				ObjectMapper objectMapper = new ObjectMapper();
				String reqJsonStr = objectMapper.writeValueAsString(search);
				JSONObject reqObj = new JSONObject(reqJsonStr);
				log.info(LOG_PREFIX+ "Request {}", reqObj);
				
				// 여기서 부터 로직
				log.info(LOG_PREFIX + "CmnSearch::"+search.toString());
		    	
				List<HashMap<String, Object>> list = settingService.getSettingSkinList(search);
				responseData.put("list", list);
				
				
			} catch(Exception e) {
				log.info(e.toString());
				apiResponse.setResultCode("99995");
				apiResponse.setResultMessage("token is no valid");
				return apiResponse;
			}
			
			apiResponse.setData(responseData);
			apiResponse.success();
			
		} catch (Exception e) {
			e.printStackTrace();
			apiResponse.fail();
		}
		
		return apiResponse;
	}
	
	
	@ResponseBody	
	@PostMapping("/vendor/save")
    public ApiResponse settingVendorSave(@RequestHeader String token, HttpServletRequest request, @RequestBody List<SiteVendorSkinVO> param) throws Exception {
		ApiResponse apiResponse = new ApiResponse();
		
		try {
			Site site = siteService.getSiteInfoAPI(request);
			if(site == null) {
				apiResponse.setResultCode("9999");
				apiResponse.setResultMessage("Authorization apiKey check");
				return apiResponse;
			}
			
			if( !( site.getSiteIp()==null || "".equals(site.getSiteIp())
					|| "3.3.3.3".equals(site.getSiteIp()) || site.getSiteIp().indexOf(IPKit.getIpAddressByRequest(request)) >= 0) ) {
				log.error("site.getSiteIp("+site.getSiteIp()+"), denied" + IPKit.getIpAddressByRequest(request));
				apiResponse.setResultCode("10001");
				return apiResponse;
			}
			
			// TO DO 토큰체크 
			Map responseData = new HashMap();
			
			try {
				JwtManager.TokenInfo tokenInfo = jwtManager.getTokenInfoAdmin(token);
				final String LOG_PREFIX = "#-API::SETTING::settingSkinList::"+tokenInfo.getSid()+"::::";
				
				// POJO to JSON
				ObjectMapper objectMapper = new ObjectMapper();
				String reqJsonStr = objectMapper.writeValueAsString(param);
				JSONArray reqObj = new JSONArray(reqJsonStr);
				log.info(LOG_PREFIX+ "Request {}", reqObj);
				
				// 여기서 부터 로직
				log.info(LOG_PREFIX + "List<SiteVendorSkinVO>::"+param.toString());
		    	
				for(SiteVendorSkinVO item : param) {
					if(!item.getCategory().equals("CASINO") && !item.getCategory().equals("HCASINO")) {
						item.setSkinType("A");
					}
					
					switch (item.getSkinType()) {
					case "A": item.setNexusSkinType("A");
						item.setExtrSkinType("1");
						break;
					case "B": item.setNexusSkinType("B");
						item.setExtrSkinType("2");
						break;
					case "C": item.setNexusSkinType("C");
						item.setExtrSkinType("3");
						break;
					case "D": item.setNexusSkinType("D");
						item.setExtrSkinType("4");
						break;
					case "E": item.setNexusSkinType("E");
						item.setExtrSkinType("5");
						break;
					case "F": item.setNexusSkinType("E");
						item.setExtrSkinType("6");
						break;
					case "G": item.setNexusSkinType("E");
						item.setExtrSkinType("7");
						break;
					case "H": item.setNexusSkinType("E");
						item.setExtrSkinType("8");
						break;
					case "I": item.setNexusSkinType("E");
						item.setExtrSkinType("9");
						break;
					case "J": item.setNexusSkinType("E");
						item.setExtrSkinType("10");
						break;
					default: item.setNexusSkinType("A");
						item.setExtrSkinType("1");
						break;
					}
					
					
					int saveResult = settingService.settingVendorSkinSave(item);
					log.info(LOG_PREFIX + "vendorIdx::"+item.getVendorIdx()+"::saveResult::"+saveResult);
				}
				
				
			} catch(Exception e) {
				log.info(e.toString());
				apiResponse.setResultCode("99995");
				apiResponse.setResultMessage("token is no valid");
				return apiResponse;
			}
			
			apiResponse.success();
			
		} catch (Exception e) {
			e.printStackTrace();
			apiResponse.fail();
		}
		
		return apiResponse;
	}
	
	
	@ResponseBody	
	@PostMapping("/whiteIp")
    public ApiResponse whiteIpList(@RequestHeader String token, HttpServletRequest request, @RequestBody CmnSearch search) throws Exception {
		ApiResponse apiResponse = new ApiResponse();
		
		try {
			Site site = siteService.getSiteInfoAPI(request);
			if(site == null) {
				apiResponse.setResultCode("9999");
				apiResponse.setResultMessage("Authorization apiKey check");
				return apiResponse;
			}
			
			if( !( site.getSiteIp()==null || "".equals(site.getSiteIp())
					|| "3.3.3.3".equals(site.getSiteIp()) || site.getSiteIp().indexOf(IPKit.getIpAddressByRequest(request)) >= 0) ) {
				log.error("site.getSiteIp("+site.getSiteIp()+"), denied" + IPKit.getIpAddressByRequest(request));
				apiResponse.setResultCode("10001");
				return apiResponse;
			}
			
			// TO DO 토큰체크 
			Map responseData = new HashMap();
			
			try {
				JwtManager.TokenInfo tokenInfo = jwtManager.getTokenInfoAdmin(token);
				final String LOG_PREFIX = "#-API::SETTING::whiteIpList::"+tokenInfo.getSid()+"::::";
				
				// POJO to JSON
				ObjectMapper objectMapper = new ObjectMapper();
				String reqJsonStr = objectMapper.writeValueAsString(search);
				JSONObject reqObj = new JSONObject(reqJsonStr);
				log.info(LOG_PREFIX+ "Request {}", reqObj);
				
				// 여기서 부터 로직
				if(search.getSiteIdx() == null || search.getSiteIdx() == 0) {
					apiResponse.setResultCode("9999");
					apiResponse.setResultMessage("대상이 존재하지 않습니다");
					return apiResponse;
				}
		    	log.info(LOG_PREFIX + "CmnSearch::"+search.toString());
		    	
				List<String> list = settingService.getWhiteIpList(search);
				responseData.put("list", list);
				
				
			} catch(Exception e) {
				log.info(e.toString());
				apiResponse.setResultCode("99995");
				apiResponse.setResultMessage("token is no valid");
				return apiResponse;
			}
			
			apiResponse.setData(responseData);
			apiResponse.success();
			
		} catch (Exception e) {
			e.printStackTrace();
			apiResponse.fail();
		}
		
		return apiResponse;
	}

	@ResponseBody	
	@PostMapping("/getSportsSetting")
    public ApiResponse getSportsSetting(@RequestHeader String token, HttpServletRequest request) throws Exception {
		ApiResponse apiResponse = new ApiResponse();
		
		try {
			Site site = siteService.getSiteInfoAPI(request);
			if(site == null) {
				apiResponse.setResultCode("9999");
				apiResponse.setResultMessage("Authorization apiKey check");
				return apiResponse;
			}
			
			if( !( site.getSiteIp()==null || "".equals(site.getSiteIp())
					|| "3.3.3.3".equals(site.getSiteIp()) || site.getSiteIp().indexOf(IPKit.getIpAddressByRequest(request)) >= 0) ) {
				log.error("site.getSiteIp("+site.getSiteIp()+"), denied" + IPKit.getIpAddressByRequest(request));
				apiResponse.setResultCode("10001");
				return apiResponse;
			}
			
			// TO DO 토큰체크 
			Map responseData = new HashMap();
			
			try {
				JwtManager.TokenInfo tokenInfo = jwtManager.getTokenInfoAdmin(token);
				final String LOG_PREFIX = "#-API::SETTING::getSportsSetting::"+tokenInfo.getSid()+"::::";
				
				// 여기서 부터 로직
				HashMap<String, String> apiInfo = settingService.getBetRadarApiInfo(tokenInfo.getSid());
				if(apiInfo == null || apiInfo.get("apiKey") == null) {
					apiResponse.setResultCode("8888");
					apiResponse.setResultMessage("Not found 'BetRadar' settings..");
					log.info(LOG_PREFIX+ "Not found 'BetRadar' settings..");
					return apiResponse;
				}
		    	log.info(LOG_PREFIX + "ApiInfo::"+apiInfo.toString());
		    	
				String url = betRadarService.getSportsSetting(LOG_PREFIX, apiInfo);
				responseData.put("url", url);
				
				
			} catch(Exception e) {
				e.printStackTrace();
				log.info("#-API::SETTING::getSportsSetting::"+ e.toString());
				apiResponse.setResultCode("99995");
				apiResponse.setResultMessage("token is no valid");
				return apiResponse;
			}
			
			apiResponse.setData(responseData);
			apiResponse.success();
			
		} catch (Exception e) {
			log.info("#-API::SETTING::getSportsSetting::"+ e.toString());
			e.printStackTrace();
			apiResponse.fail();
		}
		
		return apiResponse;
	}
}
