package com.upay.sdk.transferSingle;

import com.alibaba.fastjson.JSONObject;
import com.upay.sdk.FastJsonUtils;
import com.upay.sdk.exception.HmacVerifyException;
import com.upay.sdk.exception.ResponseException;
import com.upay.sdk.exception.UnknownException;
import com.upay.sdk.executer.ResultListenerAdpater;
import com.upay.sdk.transferDomestic.executer.TransferDomesticOrderExecuter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

public class NotifyServlet extends HttpServlet {
	static final Logger LOGGER = LoggerFactory.getLogger(NotifyServlet.class);
	
    private static final String ENCRYPT_KEY = "encryptKey";
    private static final String MERCHANT_ID = "merchantId";

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doPost(req, resp);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
	    LOGGER.info("NotifyServletV3 start...");
	    TransferDomesticOrderExecuter executer = new TransferDomesticOrderExecuter();
	    try{
	        
	        JSONObject json = FastJsonUtils.convert(req.getInputStream());
            json.put(ENCRYPT_KEY,req.getHeader(ENCRYPT_KEY));
            json.put(MERCHANT_ID,req.getHeader(MERCHANT_ID));
	        
		    executer.bothCipherCallback(json, new ResultListenerAdpater() {
		       
		        @Override
	            public void success(JSONObject jsonObject) {
	                LOGGER.info("转账成功！");
	                LOGGER.info(jsonObject.toJSONString());
	            }
	            
		        @Override
	            public void failure(JSONObject jsonObject) {
	                LOGGER.info("转账失败！",jsonObject);
	                LOGGER.info(jsonObject.toJSONString());
	            }
	            
		        @Override
	            public void processing(JSONObject jsonObject) {
	            	LOGGER.info("转账处理中！");
	                LOGGER.info(jsonObject.toJSONString());
	            }
	        });
	    }
		catch(ResponseException e){
			LOGGER.error("NotifyServlet v3 响应异常", e);
		}
		catch(HmacVerifyException e){
			LOGGER.error("NotifyServlet v3 签名验证异常", e);
		}
		catch(UnknownException e){
			LOGGER.error("NotifyServlet v3 未知异常", e);
		}
	    
	    LOGGER.info("NotifyServletV3 notify success...");
		PrintWriter out = resp.getWriter();
		out.print("SUCCESS");
	}
}
