package com.bb.api;

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

import jakarta.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
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 org.springframework.web.bind.annotation.RestController;

import com.bb.jwt.JwtClame;
import com.bb.jwt.JwtManager;
import com.bb.model.ApiResponse;
import com.bb.model.BoardSearch;
import com.bb.model.PageFormVO;
import com.bb.model.Site;
import com.bb.model.SiteSearch;
import com.bb.service.SiteService;
import com.bb.service.StatService;
import com.bb.util.IPKit;
import com.bb.util.PagingUtil;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONObject;

@Slf4j
@RestController
@RequiredArgsConstructor
@RequestMapping(value = "/api/v1")
public class ApiMainController {
	
	@Autowired
	private final JwtManager jwtManager;
	
	@Autowired
	SiteService siteService;
	

	@Autowired
	StatService statService;
	
	 
	@ResponseBody
	@PostMapping(value="/login")
	public ApiResponse agentBalance(HttpServletRequest request, @RequestBody JSONObject requestBody) throws Exception {
		ApiResponse apiResponse = new ApiResponse();
		final String LOG_PREFIX = "#-NSOFT::LOGIN::"+requestBody.getString("apiId")+":::";
		try {
			// apiKey 체크
			log.info(LOG_PREFIX+ "Request Body: "+requestBody.toString());
			String agentId = requestBody.getString("apiId");
			if(agentId != null && "tripleSuper".equals(agentId)){
				apiResponse.setResultCode("9991");
				apiResponse.setResultMessage("Super admin login is not allow");
				return apiResponse;
			}
			
			if("".equals(agentId)) {
				apiResponse.setResultCode("9998");
				apiResponse.setResultMessage("apiId is not null");
				return apiResponse;
			}
			
			String agentPwd = requestBody.getString("apiPwd");
			if("".equals(agentPwd)) {
				apiResponse.setResultCode("9998");
				apiResponse.setResultMessage("agentPwd is not null");
				return apiResponse;
			}
			Map loginParam = new HashMap();
			loginParam.put("siteId", agentId);
			loginParam.put("sitePwd", agentPwd);
			
			Site siteLogin = siteService.getSiteLoginApi(loginParam);	
			if(siteLogin == null) {
				apiResponse.setResultCode("9997");
				apiResponse.setResultMessage("agent info check");
				return apiResponse;
			}
			
			log.info(siteLogin.getIps() +","+IPKit.getIpAddressByRequest(request) );
			if( !( siteLogin.getIps() == null  ||  "".equals(siteLogin.getIps())  ||  "3.3.3.3".equals(siteLogin.getIps())  ||  siteLogin.getIps().indexOf(IPKit.getIpAddressByRequest(request)) >= 0 ) ) {
				log.error("#API::LOGIN::"+siteLogin.getSiteId() +"::siteLogin.getIps("+siteLogin.getIps()+"), denied" + IPKit.getIpAddressByRequest(request));
				apiResponse.setResultCode("10001");
				apiResponse.setResultMessage("access denied IP");
				return apiResponse;
			}			
			
			JwtClame jwtinfo = new JwtClame();
			jwtinfo.setSiteId(siteLogin.getSiteId());
			String token = jwtManager.generateTokenAdmin(jwtinfo);
			String refresh_token = jwtManager.generateTokenRefresh(jwtinfo);
			
			Map data = new HashMap();
			data.put("siteKey", siteLogin.getSiteKey());
			data.put("token", token);
			data.put("refresh_token", refresh_token);
			data.put("isTransfer", siteLogin.getIsTransfer());
			data.put("useParseStatMenu", siteLogin.getUseParseStatMenu());
			log.info("#API::LOGIN::data::" + data.toString());
			
			apiResponse.setData(data);
			apiResponse.success();
			
		} catch (Exception e) {
		
			e.printStackTrace();
			apiResponse.fail();
		}
		
		return apiResponse;
	}
	
	
	@ResponseBody
	@PostMapping(value="/myCredit")
	public ApiResponse myCredit(@RequestHeader String token, HttpServletRequest request) throws Exception {
		ApiResponse apiResponse = new ApiResponse();
		try {
			log.info(token.toString());
			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");
				apiResponse.setResultMessage("access denied IP");
				return apiResponse;
			}			
			//토큰체크	
			Map data = new HashMap();
			
			try {
				JwtManager.TokenInfo tokenInfo = jwtManager.getTokenInfoAdmin(token);
				
				log.info(tokenInfo.getSid());
				long siteCredit = siteService.getSiteCredit(tokenInfo.getSid());
				long sitePoint = siteService.getSitePoint(tokenInfo.getSid());
				data.put("credit", siteCredit);
				data.put("point", sitePoint);
				data.put("siteLevel", site.getSiteLevel());
				if(site.getSiteLevel() == 1) {
					HashMap creditInfo = siteService.getSiteSubCredit(tokenInfo.getSid());
					data.put("subCreditInfo", creditInfo);
				} else {
					data.put("subCreditInfo", null);
				}
				
			} catch(Exception e) {
				log.info(e.toString());
				apiResponse.setResultCode("99995");
				apiResponse.setResultMessage("token is no valid");
				return apiResponse;
			}
			
			apiResponse.setData(data);
			apiResponse.success();
			
		} catch (Exception e) {
			e.printStackTrace();
			apiResponse.fail();
		}
		
		return apiResponse;
	}
	
	
	@ResponseBody
	@PostMapping(value="/myBetInfo")
	public ApiResponse myBetInfo(@RequestHeader String token, HttpServletRequest request, @RequestBody JSONObject param) throws Exception {
		ApiResponse apiResponse = new ApiResponse();
		try {
			log.info(token.toString());
			String authorization = request.getHeader("Authorization").toString();
			log.info("#-myBetInfo::Authorization::"+authorization);
			log.info("#-myBetInfo::param::"+param);
			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");
				apiResponse.setResultMessage("access denied IP");
				return apiResponse;
			}			
			// TO DO 토큰체크 
			Map data = new HashMap();
			
			try {
			JwtManager.TokenInfo tokenInfo = jwtManager.getTokenInfoAdmin(token);
			
			log.info("#-myBetInfo::site::"+tokenInfo.getSid());
		
			SiteSearch search = new SiteSearch();
			search.setSiteIdx(site.getSiteIdx());
			search.setStartDate(param.getString("targetDate"));
			log.info("#-myBetInfo::search::"+search);
			List<HashMap>  stat = statService.getDashBoardList(search)	;
			data.put("info", stat);
			
			List<HashMap>  statM = statService.getDashBoardMonth(search)	;
			data.put("infoM", statM);
			
			} catch(Exception e) {
				log.info(e.toString());
				apiResponse.setResultCode("99995");
				apiResponse.setResultMessage("token is no valid");
				return apiResponse;
			}
			
			apiResponse.setData(data);
			apiResponse.success();
			
		} catch (Exception e) {
			log.error("#-myBetInfo::Exception::"+ e.getMessage());
			e.printStackTrace();
			apiResponse.fail();
		}
		
		return apiResponse;
	}
	
	
	@ResponseBody	
	@PostMapping("/board/list")
    public ApiResponse boardList(@RequestHeader String token, HttpServletRequest request, @RequestBody BoardSearch 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::MAIN::boardList::"+tokenInfo.getSid()+"::::";
				
				// 여기서 부터 로직
				search.setSiteIdx(site.getSiteIdx());
				search.setSiteId(tokenInfo.getSid());
				log.info(LOG_PREFIX + "BoardSearch::"+search);
				
				if(search.getViewType() == null || search.getViewType().equals("")) {
					search.setViewType("main");
				}
				
				if(search.getBoardType() == null || search.getBoardType().equals("")) {
					search.setBoardType("notice");
				}
				
		    	if(search.getViewType().equals("main")) {
		    		List<HashMap<String, Object>> list = siteService.getBoardList(search);
					responseData.put("boardList", list);
		    	} else {
		    		PageFormVO pageVo = new PageFormVO();
		    		int totalCount = siteService.getBoardListCnt(search);
		    		if (totalCount != 0) {
						PageFormVO commonForm = new PageFormVO();
						commonForm.setFunction_name("goPage");
						commonForm.setPage(search.getPage());
						commonForm.setCount_per_page(20);
						if(search.getCount_per_list()==0) {
							commonForm.setCount_per_list(30);
						} else {
							commonForm.setCount_per_list(search.getCount_per_list());
						}
						commonForm.setTatal_list_count(totalCount);
						pageVo = PagingUtil.setPageUtil(commonForm);
						search.setLimit(pageVo.getLimit());
						search.setOffset(pageVo.getOffset());
						search.setTatal_list_count(totalCount);
						
						responseData.put("pageInfo", pageVo);
					}
		    		
		    		List<HashMap<String, Object>> list = siteService.getBoardList(search);
					responseData.put("boardList", 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	
	@GetMapping("/board/{boardIdx}")
    public ApiResponse boardList(@RequestHeader String token, HttpServletRequest request, @PathVariable long boardIdx) 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::MAIN::boardList::"+tokenInfo.getSid()+"::::";
				
				// 여기서 부터 로직
		    	log.info(LOG_PREFIX + "BoardIdx::"+boardIdx);
		    	
		    	HashMap<String, Object> detail = siteService.getBoardDetail(boardIdx);
				responseData.put("boardDetail", detail);
				
			} 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;
	}
}
