package com.njcn.advance.utils;

import lombok.extern.slf4j.Slf4j;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStream;

/**
 * pqs
 *
 * @author cdf
 * @date 2023/6/20
 */
@Slf4j
public class JnaCallDllOrSo {
    private String path = "";


    public JnaCallDllOrSo(String name) {
        super();
        try {
            String os = System.getProperty("os.name");
            int beginIndex = os != null && os.startsWith("Windows") ? 1 : 0;
            String nameDll;
            if (beginIndex == 0) {
                nameDll = "lib" + name + ".so";
            } else {
                nameDll = name;
                if (!name.endsWith(".dll")) {
                    nameDll = name + ".dll";
                }
            }

            String tem = "/usr/local/dllFile/"+ nameDll;
            File dockerFile = new File(tem);
            if(!dockerFile.exists()){
                boolean f = dockerFile.getParentFile().mkdirs();
                boolean d = dockerFile.createNewFile();
                System.out.println("文件夹创建："+f);
                System.out.println("文件创建："+d);

                try (InputStream inputStream = getClass().getClassLoader().getResourceAsStream(nameDll)) {
                    if (inputStream == null) {
                        log.error("找不到资源文件: {}", nameDll);
                        throw new FileNotFoundException("找不到资源文件: " + nameDll);
                    }
                    try (FileOutputStream outputStream = new FileOutputStream(dockerFile)) {
                        byte[] buffer = new byte[1024];
                        int bytesRead;
                        while ((bytesRead = inputStream.read(buffer)) != -1) {
                            outputStream.write(buffer, 0, bytesRead);
                        }
                    }
                }
            }
            this.path = dockerFile.getAbsolutePath();
            System.out.println("动态库路径: " + this.path);
        } catch (Exception e) {
            log.error("调用高级算法文件异常，异常信息如下：");
            log.error(e.getMessage(), e);
            throw new RuntimeException("加载动态库失败: " + e.getMessage(), e);
        }


    }


    public String getStrpath() {
        return this.path;
    }

    public void setPath() {

    }
}
