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

import com.alibaba.fastjson.JSONObject;
import com.chenyang.nse.bussiness.config.PropertiesLoaderUtils;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import org.apache.commons.lang.StringUtils;

public class AuditLogUtil {
   private static String fileName = "";

   public static ArrayList<JSONObject> toArrayByFileReader() {
      Properties props = new Properties();

      try {
         props = PropertiesLoaderUtils.loadAllProperties("config.properties");
      } catch (IOException e) {
         e.printStackTrace();
      }

      String filepath = props.getProperty("appserverlogpath");
      List<String> fileNames = new ArrayList();
      FileUtil.findFileList(new File(filepath), fileNames);
      ArrayList<JSONObject> arrayList = new ArrayList();
      fileNames.stream().forEach((fileName) -> readFile(arrayList, fileName));
      return arrayList;
   }

   private static void readFile(ArrayList<JSONObject> arrayList, String fileName) {
      try {
         InputStream fr = new FileInputStream(fileName);
         BufferedReader bf = new BufferedReader(new InputStreamReader(fr));

         String str;
         while((str = bf.readLine()) != null) {
            JSONObject jsonObject = JSONObject.parseObject(str);
            arrayList.add(jsonObject);
         }

         bf.close();
         fr.close();
      } catch (IOException e) {
         e.printStackTrace();
      }

   }

   public static ArrayList<JSONObject> toArrayByFileReaderOfDb(String logType) {
      Properties props = new Properties();

      try {
         props = PropertiesLoaderUtils.loadAllProperties("config.properties");
      } catch (IOException e) {
         e.printStackTrace();
      }

      String filepath = "";
      if (StringUtils.isBlank(logType)) {
         return null;
      } else {
         if (logType.equals("0")) {
            filepath = props.getProperty("dbaccesslogpath");
         } else if (logType.equals("1")) {
            filepath = props.getProperty("dbrulelogpath");
         }

         List<String> fileNames = new ArrayList();
         FileUtil.findFileList(new File(filepath), fileNames);
         ArrayList<JSONObject> arrayList = new ArrayList();
         fileNames.stream().forEach((fileName) -> readFile(arrayList, fileName));
         return arrayList;
      }
   }
}
