package com.palacesun.masking.tools;

import com.palacesun.engine.gateway.EncryptionGatewayManager;
import com.palacesun.masking.tools.ruleload.RuleLoadUtil;
import com.palacesun.masking.vo.ConnectionInfo;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.sql.DatabaseMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.apache.shiro.SecurityUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

public class ConnectionUtil {
   public static final Map<Integer, ConnectionInfo> dbConinfoList = new HashMap();

   public static ConnectionInfo getConnectionInfo() throws SQLException {
      ConnectionInfo conInfo = null;
      ServletRequestAttributes attributes = (ServletRequestAttributes)RequestContextHolder.getRequestAttributes();
      HttpServletRequest request = attributes.getRequest();
      HttpSession session = request.getSession();
      if (session != null) {
         DatabaseMetaData metaData = (DatabaseMetaData)session.getAttribute("metaData");
         if (metaData != null) {
            conInfo = new ConnectionInfo();
            String userName = "";
            String schema = "";
            String url = metaData.getURL();
            String driverName = metaData.getDriverName().toLowerCase();
            if (driverName.contains("oracle")) {
               userName = metaData.getUserName();
            } else if (driverName.contains("dm")) {
               userName = metaData.getUserName();
            } else if (driverName.contains("postgresql")) {
               userName = metaData.getUserName();
            } else if (driverName.contains("sql server")) {
               userName = metaData.getUserName();
            } else if (driverName.contains("kingbase")) {
               userName = metaData.getUserName();
            } else {
               userName = metaData.getUserName().substring(0, metaData.getUserName().indexOf(64));
               schema = url.substring(url.indexOf("/", 15) + 1, url.indexOf(63));
            }

            conInfo.setUserName(userName);
            conInfo.setUrl(url);
            String testip = (String)metaData.getConnection().getClientInfo().get("ip");
            conInfo.setSchema(schema);
            String clientUsername = (String)request.getSession().getAttribute("ghca-username");
            conInfo.setClientUsername(clientUsername);
            String clientIp = RequestUtil.getRequestIp(request);
            conInfo.setClientIp(clientIp);
         }
      }

      return conInfo;
   }

   public static ConnectionInfo getConnectionInfo(DatabaseMetaData metaData) throws SQLException {
      ConnectionInfo conInfo = null;
      ServletRequestAttributes attributes = (ServletRequestAttributes)RequestContextHolder.getRequestAttributes();
      String clientIp = "";
      if (attributes != null) {
         HttpServletRequest request = attributes.getRequest();
         clientIp = RequestUtil.getRequestIp(request);
      }

      if (metaData != null) {
         conInfo = new ConnectionInfo();
         String userName = "";
         String schema = "";
         String url = metaData.getURL();
         String driverName = metaData.getDriverName().toLowerCase();
         if (driverName.contains("oracle")) {
            userName = metaData.getUserName();
         } else if (driverName.contains("dm")) {
            userName = metaData.getUserName();
         } else if (driverName.contains("postgresql")) {
            userName = metaData.getUserName();
         } else if (driverName.contains("sql server")) {
            userName = metaData.getUserName();
         } else if (driverName.contains("kingbase")) {
            userName = metaData.getUserName();
         } else {
            userName = metaData.getUserName().substring(0, metaData.getUserName().indexOf(64));
            int idx = url.indexOf(63);
            schema = url.substring(url.indexOf("/", 15) + 1, idx < 0 ? url.length() : idx);
         }

         conInfo.setUserName(userName);
         conInfo.setUrl(url);
         String testip = (String)metaData.getConnection().getClientInfo().get("ip");
         conInfo.setSchema(schema);
         conInfo.setClientIp(clientIp);
      }

      return conInfo;
   }

   public static List<String> getIps(String ipString) {
      String regEx = "((2[0-4]\\d|25[0-5]|[01]?\\d\\d?)\\.){3}(2[0-4]\\d|25[0-5]|[01]?\\d\\d?)";
      List<String> ips = new ArrayList();
      Pattern p = Pattern.compile(regEx);
      Matcher m = p.matcher(ipString);

      while(m.find()) {
         String result = m.group();
         ips.add(result);
      }

      return ips;
   }

   public static String getLoginUser() {
      String getUserType = EncryptionGatewayManager.getParameterValue("getUserType");
      String username = "";

      try {
         if ("0".equals(getUserType)) {
            username = getRyLoginUser();
         } else if ("1".equals(getUserType)) {
            username = getMaskingLoginUser();
         } else if ("2".equals(getUserType)) {
            username = getFineReportLoginUser();
         } else {
            username = getAppLoginUser();
         }

         return username;
      } catch (Exception e) {
         e.printStackTrace();
         return "";
      }
   }

   public static String getRequestUrl() {
      String url = "";
      ServletRequestAttributes attributes = (ServletRequestAttributes)RequestContextHolder.getRequestAttributes();
      if (attributes != null) {
         HttpServletRequest request = attributes.getRequest();
         url = request.getRequestURL().toString();
      }

      return url;
   }

   static String getRyLoginUser() {
      String username = "unLogin";
      ServletRequestAttributes attributes = (ServletRequestAttributes)RequestContextHolder.getRequestAttributes();
      if (attributes == null) {
         return username;
      } else {
         HttpServletRequest request = attributes.getRequest();
         HttpSession session = request.getSession();
         String focusWays_username = (String)session.getAttribute("focusWays_username");
         if (focusWays_username != null && !"".equals(focusWays_username)) {
            return focusWays_username;
         } else {
            Object loginUser = null;
            String userName = "";

            try {
               loginUser = SecurityUtils.getSubject().getPrincipal();
               if (loginUser == null) {
                  return username;
               }

               Class c = loginUser.getClass();
               Field userNameField = c.getDeclaredField("loginName");
               userNameField.setAccessible(true);
               userName = (String)userNameField.get(loginUser);
            } catch (Exception var9) {
               return username;
            }

            if (userName == null) {
               return username;
            } else {
               System.out.println("进行处理~~~~~~~~~~~~~~~~~,当前登录用户:" + userName);
               session.setAttribute("focusWays_username", userName);
               return username;
            }
         }
      }
   }

   static String getFineReportLoginUser() {
      try {
         RuleLoadUtil.writeLog("@@插件@@---getFineReportLoginUser--1111>");
         Class<?> calculatorClass = Class.forName("com.fr.script.Calculator");
         RuleLoadUtil.writeLog("@@插件@@---getFineReportLoginUser--2222>");
         Method createCalculatorMethod = calculatorClass.getMethod("createCalculator");
         RuleLoadUtil.writeLog("@@插件@@---getFineReportLoginUser--3>");
         Object calculatorInstance = createCalculatorMethod.invoke(null);
         RuleLoadUtil.writeLog("@@插件@@---getFineReportLoginUser--4>");
         Method evalMethod = calculatorClass.getMethod("eval", String.class);
         RuleLoadUtil.writeLog("@@插件@@---getFineReportLoginUser--5>");
         Object userName = evalMethod.invoke(calculatorInstance, "=$fine_username");
         RuleLoadUtil.writeLog("@@插件@@---getFineReportLoginUser--6>");
         RuleLoadUtil.writeLog("登录账号：" + userName.toString());
         if (userName == null) {
            return "";
         }

         return userName.toString();
      } catch (ClassNotFoundException e) {
         System.out.println("类未找到: " + e.getMessage());
      } catch (NoSuchMethodException e) {
         System.out.println("方法未找到: " + e.getMessage());
      } catch (Exception e) {
         System.out.println("发生异常: " + e.getMessage());
      }

      return "";
   }

   static String getAppLoginUser() {
      String username = "";
      ServletRequestAttributes attributes = (ServletRequestAttributes)RequestContextHolder.getRequestAttributes();
      if (attributes == null) {
         return username;
      } else {
         HttpServletRequest request = attributes.getRequest();
         HttpSession session = request.getSession();
         String focusWays_username = (String)session.getAttribute("focusWays_username");
         return focusWays_username != null && !"".equals(focusWays_username) ? focusWays_username : username;
      }
   }

   static String getMaskingLoginUser() {
      String username = "unLogin";
      ServletRequestAttributes attributes = (ServletRequestAttributes)RequestContextHolder.getRequestAttributes();
      if (attributes == null) {
         return username;
      } else {
         HttpServletRequest request = attributes.getRequest();
         HttpSession session = request.getSession();
         String focusWays_username = (String)session.getAttribute("focusWays_username");
         if (focusWays_username != null && !"".equals(focusWays_username)) {
            return focusWays_username;
         } else {
            String userName = "";

            try {
               String token = request.getHeader("token");
               if (token == null || "".equals(token)) {
                  return username;
               }

               userName = TokenUtil.getUserId(token);
            } catch (Exception var7) {
               return username;
            }

            if (userName == null) {
               return username;
            } else {
               System.out.println("进行处理~~~~~~~~~~~~~~~~~,当前登录用户:" + userName);
               session.setAttribute("focusWays_username", userName);
               return username;
            }
         }
      }
   }
}
