package com.upay.sdk.transferSingle;

import com.alibaba.fastjson.JSONObject;
import com.upay.sdk.exception.HmacVerifyException;
import com.upay.sdk.exception.RequestException;
import com.upay.sdk.exception.ResponseException;
import com.upay.sdk.exception.UnknownException;
import com.upay.sdk.executer.ResultListenerAdpater;
import com.upay.sdk.transferDomestic.builder.GenerateTransferVoucherBuilder;
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 GenerateTransferVoucherServlet extends HttpServlet {
    static final Logger LOGGER = LoggerFactory.getLogger(GenerateTransferVoucherServlet.class);

	@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 {

	    
		String merchantId = req.getParameter("merchantId");
		String requestId = req.getParameter("requestId");
		String remitRequestId = req.getParameter("remitRequestId");
		String partnerId = req.getParameter("partnerId");
		GenerateTransferVoucherBuilder builder = new GenerateTransferVoucherBuilder(merchantId);
		builder.setRequestId(requestId);
		builder.setRemitRequestId(remitRequestId).setPartnerId(partnerId);

		final PrintWriter out = resp.getWriter();

		TransferDomesticOrderExecuter executer = new TransferDomesticOrderExecuter();
		try{
			executer.bothGenerateTransferVoucher(builder, new ResultListenerAdpater() {
			    @Override
	            public void success(JSONObject jsonObject) {
	                out.println("处理成功！<br/>");
	                String result = jsonObject.toJSONString();
	                out.print(result);
	            }

			    @Override
	            public void failure(JSONObject jsonObject) {
	                out.println("处理失败！<br/>");
	                String result = jsonObject.toJSONString();
	                out.print(result);
	            }
	            
			    @Override
	            public void pending(JSONObject jsonObject) {
	                out.println("处理中！<br/>");
	                String result = jsonObject.toJSONString();
	                out.print(result);
	            }
			});
		}
		catch(ResponseException e){
			out.println("响应异常</br>");
			out.println(e.toString());
		}
		catch(HmacVerifyException e){
			out.println("签名验证异常</br>");
			out.println(e.toString());
		}
		catch(RequestException e){
			out.println("请求异常</br>");
			out.println(e.toString());
		}
		catch(UnknownException e){
			out.println("未知异常</br>");
			out.println(e.toString());
		}
	}
}
