package com.palacesun.masking.tools.ruleload;

import com.palacesun.engine.common.ClientUtil;
import com.palacesun.engine.gateway.EncryptionGatewayManager;
import com.palacesun.engine.gateway.util.GatewaySocketLogUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.palacesun.masking.adapter.StringUtils;
import com.palacesun.masking.tools.EngineUtil;
import org.apache.http.Header;
import org.apache.http.HttpHost;
import org.apache.http.HttpRequest;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.message.BasicNameValuePair;
import java.io.BufferedWriter;
import java.io.ByteArrayOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.logging.Logger;

public class RuleLoadUtil {
   protected static Logger logger = Logger.getLogger(RuleLoadUtil.class.getName());
   protected static CloseableHttpClient httpClient = null;
   public static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
   public static String encryptionRuleStr;
   public static String digestRuleStr;

   public static boolean isEncryptionRuleFromGateway() {
      return "gateway".equalsIgnoreCase(RuleProps.getInstance().getEncryptionRuleOrigin());
   }

   public static boolean isMaskingRuleFromGateway() {
      return "gateway".equalsIgnoreCase(RuleProps.getInstance().getMaskingRuleOrigin());
   }

   private static void initHttpClient() {
      httpClient = ClientUtil.getWrapClient();
   }

   private static void closeHttpClient() {
      if (httpClient != null) {
         try {
            httpClient.close();
         } catch (IOException e) {
            logger.warning(String.format("[%s][%s]", e.getClass().getName(), e.getMessage()));
         }

      }
   }

   public static ArrayList<JSONArray> loadEncryptionRuleFromGateway() {
      Object var0;
      try {
         encryptionRuleStr = fetchEncryptionRuleFromteway();
         if (!StringUtils.isEmpty(encryptionRuleStr)) {
            if (encryptionRuleStr.contains("OOW_01")) {
               GatewaySocketLogUtil.writeLog("当前客户端不在白名单范围内，拉取加密规则失败！");
               EngineUtil.encryptionMap.clear();
               var0 = null;
               return (ArrayList<JSONArray>)var0;
            }

            JSONArray array = JSONObject.parseArray(encryptionRuleStr);
            ArrayList<JSONArray> list = new ArrayList();
            list.add(array);
            logger.info("loadencryptionrule.success");
            ArrayList var2 = list;
            return var2;
         }

         var0 = null;
      } finally {
         closeHttpClient();
      }

      return (ArrayList<JSONArray>)var0;
   }

   public static ArrayList<JSONArray> loadDigestRuleFromGateway() {
      Object var0;
      try {
         digestRuleStr = fetchDigestRuleFromteway();
         if (!StringUtils.isEmpty(digestRuleStr)) {
            if (digestRuleStr.contains("OOW_01")) {
               GatewaySocketLogUtil.writeLog("当前客户端不在白名单范围内，拉取完整性校验规则失败！");
               EngineUtil.digestMap.clear();
               var0 = null;
               return (ArrayList<JSONArray>)var0;
            }

            JSONArray array = JSONObject.parseArray(digestRuleStr);
            ArrayList<JSONArray> list = new ArrayList();
            list.add(array);
            logger.info("loaddigestrule.success");
            ArrayList var2 = list;
            return var2;
         }

         var0 = null;
      } finally {
         closeHttpClient();
      }

      return (ArrayList<JSONArray>)var0;
   }

   private static String fetchEncryptionRuleFromteway() {
      GatewaySocketLogUtil.writeLog("执行" + (new Exception()).getStackTrace()[0].getMethodName() + "方法开始！");
      String projectid = EncryptionGatewayManager.getParameterValue("projectid");
      String uri = "/core/encryptionrule";
      uri = uri + "?projectId=" + projectid;
      uri = uri + "&remotePort=" + EncryptionGatewayManager.ROOT_PORT;

      String body;
      try {
         String gatewayHost = EncryptionGatewayManager.getParameterValue("gatewayurl");
         body = ClientUtil.doPost(gatewayHost + uri, "{}");
         GatewaySocketLogUtil.writeLog(uri + "接口返回的内容为：" + body);
         String var4 = body;
         return var4;
      } catch (RuleLoadException var9) {
         GatewaySocketLogUtil.writeLog("执行" + (new Exception()).getStackTrace()[0].getMethodName() + "方法异常！");
         body = null;
      } catch (Exception var10) {
         GatewaySocketLogUtil.writeLog("执行" + (new Exception()).getStackTrace()[0].getMethodName() + "方法异常！");
         body = null;
         return body;
      } finally {
         GatewaySocketLogUtil.writeLog("执行" + (new Exception()).getStackTrace()[0].getMethodName() + "方法结束！");
      }

      return body;
   }

   private static String fetchDigestRuleFromteway() {
      GatewaySocketLogUtil.writeLog("执行" + (new Exception()).getStackTrace()[0].getMethodName() + "方法开始！");
      String projectid = EncryptionGatewayManager.getParameterValue("projectid");
      String uri = "/core/digestrule";
      uri = uri + "?projectId=" + projectid;
      uri = uri + "&remotePort=" + EncryptionGatewayManager.ROOT_PORT;

      String body;
      try {
         String gatewayHost = EncryptionGatewayManager.getParameterValue("gatewayurl");
         body = ClientUtil.doPost(gatewayHost + uri, "{}");
         logger.info(body);
         GatewaySocketLogUtil.writeLog(uri + "接口返回的内容为：" + body);
         String var4 = body;
         return var4;
      } catch (RuleLoadException var9) {
         GatewaySocketLogUtil.writeLog("执行" + (new Exception()).getStackTrace()[0].getMethodName() + "方法异常！");
         body = null;
      } catch (Exception var10) {
         GatewaySocketLogUtil.writeLog("执行" + (new Exception()).getStackTrace()[0].getMethodName() + "方法异常！");
         body = null;
         return body;
      } finally {
         GatewaySocketLogUtil.writeLog("执行" + (new Exception()).getStackTrace()[0].getMethodName() + "方法结束！");
      }

      return body;
   }

   private static String copyToString(InputStream is) throws IOException {
      return new String(copyToByteArray(is), "utf-8");
   }

   private static byte[] copyToByteArray(InputStream is) throws IOException {
      ByteArrayOutputStream baos = new ByteArrayOutputStream();
      byte[] buffer = new byte[1024];

      for(int num = is.read(buffer); num != -1; num = is.read(buffer)) {
         baos.write(buffer, 0, num);
      }

      return baos.toByteArray();
   }

   public static ArrayList<JSONArray> loadMaskingRuleFromGateway() {
      ArrayList var3;
      try {
         initHttpClient();
         String encryptionRuleStr = fetchMaskingRuleFromteway();
         JSONArray array = JSONObject.parseArray(encryptionRuleStr);
         ArrayList<JSONArray> list = new ArrayList();
         list.add(array);
         logger.info("loadmaskingrule.success");
         var3 = list;
      } finally {
         closeHttpClient();
      }

      return var3;
   }

   private static String fetchMaskingRuleFromteway() {
      HttpPost httpPost = new HttpPost("/core/maskrule");

      String resinfo;
      try {
         httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded");
         String projectid = EncryptionGatewayManager.getParameterValue("projectid");
         if (projectid != null && !projectid.equals("")) {
            List<NameValuePair> nvps = new ArrayList();
            nvps.add(new BasicNameValuePair("projectid", projectid));
            UrlEncodedFormEntity entity = new UrlEncodedFormEntity(nvps);
            entity.setContentEncoding("UTF-8");
            httpPost.setEntity(entity);
         }

         String gatewayHost = EncryptionGatewayManager.getParameterValue("gatewayurl");
         String[] split = gatewayHost.split(":");
         String protocol = split[0];
         String ip = split[1].split("//")[1];
         Integer port = Integer.parseInt(split[2]);
         HttpHost httpHost = new HttpHost(ip, port, protocol);
         HttpResponse res = httpClient.execute((HttpHost)httpHost, (HttpRequest)httpPost);
         int code = res.getStatusLine().getStatusCode();
         logger.info(String.format("code=[%d]", code));
         Header rescodeHeader = res.getFirstHeader("rescode");
         String rescode = rescodeHeader != null ? rescodeHeader.getValue() : "0";
         if (!"0".equals(rescode)) {
            Header resinfoHeader = res.getFirstHeader("resinfo");
            resinfo = resinfoHeader != null ? resinfoHeader.getValue() : "";
            throw new RuleLoadException(String.format("[%s][%s]", rescode, resinfo));
         }

         String body = copyToString(res.getEntity().getContent());
         logger.info(body);
         resinfo = body;
      } catch (RuleLoadException rle) {
         throw rle;
      } catch (Exception e) {
         throw new RuleLoadException(e.getMessage(), e);
      } finally {
         httpPost.releaseConnection();
      }

      return resinfo;
   }

   public static void writeLog(String content) {
      if (EncryptionGatewayManager.checkParameterFlag("encryption.log")) {
         FileWriter fileWriter = null;
         BufferedWriter bufferedWriter = null;

         try {
            fileWriter = new FileWriter(System.getProperty("user.home") + "/encryption-proxy-plugin.log", true);
            bufferedWriter = new BufferedWriter(fileWriter);
            bufferedWriter.write(content(content));
         } catch (IOException e) {
            throw new RuntimeException(e);
         } finally {
            try {
               if (null != bufferedWriter) {
                  bufferedWriter.close();
               }
            } catch (IOException e) {
               throw new RuntimeException(e);
            }

            try {
               if (null != fileWriter) {
                  fileWriter.close();
               }
            } catch (IOException e) {
               throw new RuntimeException(e);
            }

         }

      }
   }

   public static String content(String content) {
      StringBuffer result = new StringBuffer("");
      result.append(sdf.format(new Date()) + " --> ");
      result.append(content);
      result.append("\r\n");
      return result.toString();
   }
}
