package com.chenyang.nse.bussiness.tools.utils;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import java.util.Random;
import org.apache.commons.lang.StringUtils;
import org.frameworkset.elasticsearch.ElasticSearchHelper;
import org.frameworkset.elasticsearch.boot.ElasticSearchBoot;
import org.frameworkset.elasticsearch.client.ClientInterface;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class GHCAUtils {
   private static Logger logger = LoggerFactory.getLogger(GHCAUtils.class);
   private Logger loger;
   private Map esProperties;
   private ClientInterface clientUtil;
   private Properties properties;
   private String projectBasePath;
   private HashMap<String, Date> blackList;

   public static final GHCAUtils getInstance() {
      return LazyHolder.INSTANCE;
   }

   private GHCAUtils() {
      this.loger = null;
      this.esProperties = null;
      this.clientUtil = null;
      this.properties = null;
      this.projectBasePath = "";
      this.blackList = new HashMap(16);
      this.loger = LoggerFactory.getLogger("GHCAUtils");
   }

   public void test() {
      System.out.println("hello Singleton");
   }

   public synchronized ClientInterface connectToES(String serverAddress, String port, String username, String password) {
      String esServer = serverAddress + ":" + port;
      if (this.esProperties == null) {
         this.esProperties = new HashMap();
         this.esProperties.put("elasticsearch.rest.hostNames", esServer);
         this.esProperties.put("elasticsearch.healthCheckInterval", -1);
         this.esProperties.put("elasticUser", username);
         this.esProperties.put("elasticPassword", password);
         this.esProperties.put("elasticsearch.showTemplate", "true");
         this.esProperties.put("elasticsearch.discoverHost", "true");
         this.esProperties.put("http.timeoutSocket", 60000);
         this.esProperties.put("http.timeoutConnection", 40000);
         this.esProperties.put("http.connectionRequestTimeout", 70000);
         ElasticSearchBoot.boot(this.esProperties);
         this.clientUtil = ElasticSearchHelper.getRestClientUtil();
      } else {
         if (this.clientUtil != null) {
            try {
               String healthPath = this.clientUtil.getElasticSearch().getHealthPath();
               if (healthPath != null && healthPath.contains("green")) {
                  return this.clientUtil;
               }
            } catch (Exception e) {
               logger.error("连接ES失败，重试连接", e);
            }
         }

         Random random = new Random();
         long randomTime = System.currentTimeMillis() + random.nextLong();
         String esSourceName = esServer + ":" + randomTime;
         this.esProperties.put("elasticsearch.serverNames", esSourceName);
         this.esProperties.put("elasticsearch.healthCheckInterval", -1);
         this.esProperties.put(esSourceName + ".elasticUser", username);
         this.esProperties.put(esSourceName + ".elasticPassword", password);
         this.esProperties.put(esSourceName + ".elasticsearch.rest.hostNames", esServer);
         this.esProperties.put(esSourceName + ".elasticsearch.showTemplate", "true");
         this.esProperties.put(esSourceName + ".elasticsearch.discoverHost", "true");
         this.esProperties.put(esSourceName + ".http.timeoutSocket", 60000);
         this.esProperties.put(esSourceName + ".http.timeoutConnection", 40000);
         this.esProperties.put(esSourceName + ".http.connectionRequestTimeout", 70000);
         ElasticSearchBoot.boot(this.esProperties);
         this.clientUtil = ElasticSearchHelper.getRestClientUtil(esSourceName);
      }

      return this.clientUtil;
   }

   public String getStackTrace(Exception e) {
      String temp = "";
      StringBuffer sb = new StringBuffer();
      if (e != null) {
         for(StackTraceElement element : e.getStackTrace()) {
            sb.append("\r\n\t").append(element);
         }
      }

      if (sb.length() > 0) {
         temp = sb.toString();
      }

      return temp;
   }

   public void closeDbResource(Object dbObject) {
      try {
         if (dbObject instanceof ResultSet) {
            ((ResultSet)dbObject).close();
            logger.info("关闭数据库资源：ResultSet");
         } else if (dbObject instanceof Statement) {
            ((Statement)dbObject).close();
            logger.info("关闭数据库资源：Statement");
         } else if (dbObject instanceof Connection) {
            ((Connection)dbObject).close();
            logger.info("关闭数据库资源：Connection");
         }
      } catch (Exception e) {
         String logInfo = "关闭数据源资源错误：" + this.getStackTrace(e);
         logger.error(logInfo);
      }

   }

   public Properties getProperties() {
      return this.properties;
   }

   public String getProjectBasePath() {
      return this.projectBasePath;
   }

   public synchronized void addExpireToken(String token) {
      if (StringUtils.isNotEmpty(token)) {
         this.blackList.put(token.trim(), new Date());
      }

   }

   public boolean isTokenExist(String token) {
      return this.blackList.containsKey(token);
   }

   public synchronized String getESPageData(ClientInterface clientUtil, String esIndex, int from, int pageSize) {
      String response = "";
      String dsl = "{\"from\":" + String.valueOf(from) + ",\"size\":" + pageSize + ",\"query\": {\"match_all\": {}}}";
      String esAction = esIndex.trim() + "/_search";
      response = clientUtil.executeHttp(esAction, dsl, "post");
      return response;
   }

   private static class LazyHolder {
      private static final GHCAUtils INSTANCE = new GHCAUtils();
   }
}
