package com.nbopen.api;

import com.nbopen.cl.NBClassLoader;

import java.io.*;
import java.lang.reflect.Method;
import java.net.URL;
import java.util.Enumeration;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;

public final class NBOpenSDK {
    private static final int BUFFER_SIZE = 512;
    private static final String openSDKName = "com.nbopen.sdk.OpenSDK";
    private static Class openSDK = null;
    private static Boolean isInit = false;
    private static NBClassLoader nbClassLoader = null;

    public NBOpenSDK() {
    }

    public static String getVersionInfo() {
        try {
            obtionOpenSDKClass();
            Method method = openSDK.getMethod("getVersionInfo");
            return (String)method.invoke(openSDK.newInstance());
        } catch (Exception var1) {
            var1.printStackTrace();
            return null;
        }
    }

    public static String getCurrentDate() {
        try {
            obtionOpenSDKClass();
            Method method = openSDK.getMethod("getCurrentDate");
            return (String)method.invoke(openSDK.newInstance());
        } catch (Exception var1) {
            var1.printStackTrace();
            return "";
        }
    }

    public static String getCurrentTime() {
        try {
            obtionOpenSDKClass();
            Method method = openSDK.getMethod("getCurrentTime");
            return (String)method.invoke(openSDK.newInstance());
        } catch (Exception var1) {
            var1.printStackTrace();
            return "";
        }
    }

    public static String getRandom() {
        try {
            obtionOpenSDKClass();
            Method method = openSDK.getMethod("getRandom");
            return (String)method.invoke(openSDK.newInstance());
        } catch (Exception var1) {
            var1.printStackTrace();
            return "";
        }
    }

    public static boolean init(InputStream stream) {
        try {
            if (!isInit) {
                obtionOpenSDKClass();
                Method method = openSDK.getMethod("init", InputStream.class);
                isInit = (Boolean)method.invoke(openSDK.newInstance(), stream);
            }
        } catch (Exception var2) {
            var2.printStackTrace();
            isInit = false;
        }

        return isInit;
    }

    public static boolean init(String pathOrContent) {
        try {
            if (!isInit) {
                obtionOpenSDKClass();
                Method method = openSDK.getMethod("init", String.class);
                isInit = (Boolean)method.invoke(openSDK.newInstance(), pathOrContent);
            }
        } catch (Exception var2) {
            var2.printStackTrace();
            isInit = false;
        }

        return isInit;
    }

    public static boolean updateConfig(Object configInfo) {
        try {
            obtionOpenSDKClass();
            Method method = openSDK.getMethod("updateConfig", Object.class);
            isInit = (Boolean)method.invoke(openSDK.newInstance(), configInfo);
        } catch (Exception var2) {
            var2.printStackTrace();
        }

        return isInit;
    }

    public static SDKResponse send(SDKRequest request) throws Exception {
        try {
            obtionOpenSDKClass();
            Method method = openSDK.getMethod("send", SDKRequest.class);
            return (SDKResponse)method.invoke(openSDK.newInstance(), request);
        } catch (Exception var2) {
            var2.printStackTrace();
            throw var2;
        }
    }

    public static SDKResponse encryptMessage(SDKRequest request) throws Exception {
        try {
            obtionOpenSDKClass();
            Method method = openSDK.getMethod("encryptMessage", SDKRequest.class);
            return (SDKResponse)method.invoke(openSDK.newInstance(), request);
        } catch (Exception var2) {
            var2.printStackTrace();
            throw var2;
        }
    }

    public static SDKResponse decryptMessage(SDKRequest request) throws Exception {
        try {
            obtionOpenSDKClass();
            Method method = openSDK.getMethod("decryptMessage", SDKRequest.class);
            return (SDKResponse)method.invoke(openSDK.newInstance(), request);
        } catch (Exception var2) {
            var2.printStackTrace();
            throw var2;
        }
    }

    public static SDKResponse getFile(SDKRequest request) throws Exception {
        try {
            obtionOpenSDKClass();
            Method method = openSDK.getMethod("getFileByHttp", SDKRequest.class);
            return (SDKResponse)method.invoke(openSDK.newInstance(), request);
        } catch (Exception var2) {
            var2.printStackTrace();
            throw var2;
        }
    }

    public static SDKResponse putFile(SDKRequest request) throws Exception {
        try {
            obtionOpenSDKClass();
            Method method = openSDK.getMethod("putFileByHttp", SDKRequest.class);
            return (SDKResponse)method.invoke(openSDK.newInstance(), request);
        } catch (Exception var2) {
            var2.printStackTrace();
            throw var2;
        }
    }

    private static void obtionOpenSDKClass() throws ClassNotFoundException {
        if (openSDK == null) {
            openSDK = nbClassLoader.loadClass("com.nbopen.sdk.OpenSDK");
        }

    }

    private static String readCurrentJar(String jarPath) {
        if (!jarPath.contains("!")) {
            return jarPath;
        } else {
            if (jarPath.endsWith("!")) {
                jarPath = jarPath.substring(0, jarPath.length() - 1);
            }

            String userDir = System.getProperty("user.dir");
            System.out.println("nbsdk-userDir: " + userDir);
            File folder = new File(userDir + File.separator + "nbsdk" + File.separator + "lib");
            if (!folder.exists()) {
                try {
                    folder.mkdirs();
                } catch (Exception var7) {
                    throw new RuntimeException("mkdir failed " + folder.getPath());
                }
            }

            folder.deleteOnExit();
            String[] path = jarPath.split("!");
            String jar = path[0];
            String temp = path[1];
            if (temp.contains("openBasicSDK")) {
                temp = temp.split("openBasicSDK")[0];
            }

            printMsg("nbsdk-temp=" + temp);
            printMsg("nbsdk-temp.startWith=" + temp.startsWith(File.separator));
            if (temp.startsWith("/")) {
                temp = temp.substring(1, temp.length());
            }

            unzipJarJar(jar, temp, folder.getAbsolutePath());
            String currentJarPath = folder.getPath() + File.separator + path[1].split(temp)[1];
            printMsg("nbsdk-currentJarPath:" + currentJarPath);
            return currentJarPath;
        }
    }

    private static void unzipJarJar(String jarPath, String srcPath, String dstPath) {
        JarFile jarFile = null;
        try {
            jarFile = new JarFile(jarPath);
            Enumeration<JarEntry> entries = jarFile.entries();

            while(entries.hasMoreElements()) {
                JarEntry jarEntry = (JarEntry)entries.nextElement();
                String name = jarEntry.getName();
                printMsg("nbsdk-unzipJarJar-name=" + name + "         srcPath=" + srcPath);
                String[] split = name.split(srcPath);
                printMsg("nbsdk-unzipJarJar-split.length = " + split.length);
                if (name.startsWith(srcPath) && split.length == 2) {
                    String jarName = split[1];
                    printMsg("nbsdk-unzipJarJar-split[0]=" + split[0]);
                    printMsg("nbsdk-unzipJarJar-split[1]=" + jarName);
                    if (jarName.startsWith("openBasicSDK")) {
                        printMsg("nbsdk-unzipJarJar-start unzip jar=" + name);
                        printMsg("nbsdk-unzipJarJar-dstPath=" + dstPath);
                        File file = new File(dstPath, jarName);
                        unpack(jarFile, jarEntry, file);
                        break;
                    }
                }
            }
        } catch (Exception var10) {
            var10.printStackTrace();
        } finally {
            if (jarFile != null) {
                try {
                    jarFile.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }

    private static File unpackToFolder(File jarPath, NBClassLoader classLoader) {
        JarFile jarFile = null;
        try {
            String userDir = System.getProperty("user.dir");
            System.out.println("nbsdk-userDir: " + userDir);
            File folder = new File(userDir + File.separator + "nbsdk" + File.separator + "lib");
            if (!folder.exists()) {
                try {
                    folder.mkdirs();
                } catch (Exception var11) {
                    throw new RuntimeException("mkdir failed " + folder.getPath());
                }
            }

            folder.deleteOnExit();
            jarFile = new JarFile(jarPath);
            Enumeration<JarEntry> entries = jarFile.entries();

            while(entries.hasMoreElements()) {
                JarEntry jarEntry = (JarEntry)entries.nextElement();
                String name = jarEntry.getName();
                String[] split = name.split("/");
                if (name.startsWith("sdklib/") && split.length > 1) {
                    File file = new File(folder, split[1]);
                    printMsg("nbsdk- unpack: " + file.getPath());
                    unpack(jarFile, jarEntry, file);
                    URL url = file.toURI().toURL();
                    printMsg("add jar to classLoader: " + url.toString());
                    classLoader.addURL(url);
                }
            }

            return folder;
        } catch (Exception var12) {
            System.out.println("nbsdk- unpack to folder error" + var12);
            throw new RuntimeException(var12);
        } finally {
            if (jarFile != null) {
                try {
                    jarFile.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    private static void unpack(JarFile jarFile, JarEntry entry, File file) throws IOException {
        printMsg("unpack jarPath = " + file.getPath());
        InputStream inputStream = jarFile.getInputStream(entry);
        Throwable var4 = null;

        try {
            OutputStream outputStream = new FileOutputStream(file);
            Throwable var6 = null;

            try {
                byte[] buffer = new byte[512];

                int bytesRead;
                while((bytesRead = inputStream.read(buffer)) != -1) {
                    outputStream.write(buffer, 0, bytesRead);
                }

                outputStream.flush();
            } catch (Throwable var30) {
                var6 = var30;
                throw var30;
            } finally {
                if (outputStream != null) {
                    if (var6 != null) {
                        try {
                            outputStream.close();
                        } catch (Throwable var29) {
                            var6.addSuppressed(var29);
                        }
                    } else {
                        outputStream.close();
                    }
                }

            }
        } catch (Throwable var32) {
            var4 = var32;
            throw var32;
        } finally {
            if (inputStream != null) {
                if (var4 != null) {
                    try {
                        inputStream.close();
                    } catch (Throwable var28) {
                        var4.addSuppressed(var28);
                    }
                } else {
                    inputStream.close();
                }
            }

        }
    }

    private static void deleteFile(File file) {
        if (file.exists()) {
            if (file.isFile()) {
                file.delete();
            } else {
                File[] listFiles = file.listFiles();
                File[] var2 = listFiles;
                int var3 = listFiles.length;

                for(int var4 = 0; var4 < var3; ++var4) {
                    File f = var2[var4];
                    deleteFile(f);
                }
            }

            file.delete();
        }

    }

    private static void printMsg(String data) {
        String debuged = System.getProperty("nbsdk.sys.debug", "false");
        if (Boolean.parseBoolean(debuged)) {
            System.out.println(data);
        }

    }

    static {
        File files = null;

        try {
            String path = NBClassLoader.class.getProtectionDomain().getCodeSource().getLocation().getPath();
            if (path.startsWith("file:")) {
                path = path.substring("file:".length(), path.length());
            }
            if (path.startsWith("nested:")) {
                path = path.substring("nested:".length(), path.length());
            }

            System.out.println("nbsdk-jarpath:" + path);
            nbClassLoader = new NBClassLoader(new URL[0], NBOpenSDK.class.getClassLoader());
            printMsg("SDK-classLoader: " + nbClassLoader);
            path = readCurrentJar(path);
            files = unpackToFolder(new File(path), nbClassLoader);
        } catch (Exception var2) {
            var2.printStackTrace();
        }

    }
}
