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

import com.chenyang.nse.bussiness.entity.vo.ResultVO;
import com.chenyang.nse.bussiness.tools.string.AesTool;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang.StringUtils;

public class LicenseKeyTool {
   public static ResultVO verifyproperties(String url) throws ClassNotFoundException, IOException, SQLException, ParseException {
      ResultVO resultVO = new ResultVO();
      Map<String, String> configMap = new HashMap();
      resultVO.setResult(true);
      File file = new File(url);
      if (file.exists()) {
         FileReader fileReader = new FileReader(file);
         BufferedReader bfReader = new BufferedReader(fileReader);
         StringBuffer stringBuffer = new StringBuffer();

         String line;
         while((line = bfReader.readLine()) != null) {
            String a = line.substring(0, line.indexOf("="));
            String b = line.substring(line.indexOf("=") + 1);
            configMap.put(a, b);
            stringBuffer.append(line);
            stringBuffer.append("\n");
         }

         String keyvalue = (String)configMap.get("key");
         resultVO = checkKey(keyvalue);
      } else {
         resultVO.setResult(false);
         resultVO.setMessage("Lack of LICENCE KEY file");
      }

      return resultVO;
   }

   private static ResultVO checkKey(String licensekey) throws ParseException, SocketException {
      ResultVO resultVO = new ResultVO();
      if (licensekey != null && !licensekey.equals("")) {
         String password = "ghca";
         String licensekeyAfter = AesTool.decrypt(licensekey, password);
         if (licensekeyAfter == null) {
            resultVO.setMessage("Incorrect key");
            resultVO.setResult(false);
            return resultVO;
         } else {
            String[] licensekeyMessage = licensekeyAfter.split(",");
            String licInfoIp = licensekeyMessage[0];
            String licInfoMac = licensekeyMessage[1];
            String startDatelicensekey = licensekeyMessage[2];
            String endDatelicensekey = licensekeyMessage[3];
            List linuxLocalIp = getLinuxLocalIp();
            List<String> linuxLocalMac = new ArrayList();

            for(Object mac : linuxLocalIp) {
               String macs = getLocalMacLiunx(mac.toString());
               linuxLocalMac.add(macs);
            }

            boolean b = false;

            for(int i = 0; i < linuxLocalIp.size(); ++i) {
               String localIp = (String)linuxLocalIp.get(i);
               String localMac = (String)linuxLocalMac.get(i);
               if (licInfoIp.equalsIgnoreCase(localIp) && licInfoMac.equalsIgnoreCase(localMac)) {
                  b = true;
                  break;
               }
            }

            if (!b) {
               resultVO.setMessage("Key IP error");
               resultVO.setResult(false);
               return resultVO;
            } else {
               SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
               Date date = new Date();
               Date startDate = sdf.parse(startDatelicensekey);
               Date endDate = sdf.parse(endDatelicensekey);
               int dayMis = 86400000;
               long startDateMis = startDate.getTime();
               long endDateMis = endDate.getTime() + (long)dayMis - 1L;
               long curDateMis = date.getTime();
               if (startDateMis <= curDateMis && curDateMis <= endDateMis) {
                  resultVO.setMessage("In force");
                  resultVO.setResult(true);
                  return resultVO;
               } else {
                  resultVO.setMessage("Your user secret key has expired");
                  resultVO.setResult(false);
                  return resultVO;
               }
            }
         }
      } else {
         resultVO.setMessage("The key is empty");
         resultVO.setResult(false);
         return resultVO;
      }
   }

   private static List getLinuxLocalIp() throws SocketException {
      List<String> ipList = new ArrayList();
      String ip = "";

      try {
         Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces();

         while(en.hasMoreElements()) {
            NetworkInterface intf = (NetworkInterface)en.nextElement();
            String name = intf.getName();
            if (!name.contains("docker") && !name.contains("lo")) {
               Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses();

               while(enumIpAddr.hasMoreElements()) {
                  InetAddress inetAddress = (InetAddress)enumIpAddr.nextElement();
                  if (!inetAddress.isLoopbackAddress()) {
                     String ipaddress = inetAddress.getHostAddress().toString();
                     if (!ipaddress.contains("::") && !ipaddress.contains("0:0:") && !ipaddress.contains("fe80")) {
                        ipList.add(ipaddress);
                     }
                  }
               }
            }
         }
      } catch (SocketException ex) {
         ip = "127.0.0.1";
         ex.printStackTrace();
      }

      return ipList;
   }

   public static String getLocalMacLiunx(String locip) throws SocketException {
      String mac = "";
      StringBuilder sb = new StringBuilder();

      try {
         InetAddress ip = InetAddress.getByName(locip);
         NetworkInterface network = NetworkInterface.getByInetAddress(ip);
         if (network != null) {
            byte[] macArr = network.getHardwareAddress();
            if (macArr != null) {
               for(int i = 0; i < macArr.length; ++i) {
                  sb.append(String.format("%02X%s", macArr[i], i < macArr.length - 1 ? "-" : ""));
               }
            }
         }
      } catch (Exception e) {
         e.printStackTrace();
      }

      mac = sb.toString();
      String osName = System.getProperties().getProperty("os.name");
      if (osName.equals("Linux") && StringUtils.isNotBlank(mac)) {
         mac = mac.replace("-", ":");
      }

      return mac;
   }

   public static void main(String[] args) {
      String content = "192.168.2.134,0:0c:29:7e:f5:e0,2022-08-01,2023-08-01";
      String password = "ghca";
      System.out.println("加密之前：" + content);
      String encrypt = AesTool.encrypt(content, password);
      System.out.println("加密后的内容：" + encrypt);
      String decrypt = AesTool.decrypt(encrypt, password);
      System.out.println("解密后的内容：" + new String(decrypt));
   }
}
