package com.zy.QrDecode;

import com.sun.jna.Platform;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.system.ApplicationHome;

import java.io.File;
import java.io.UnsupportedEncodingException;

@Slf4j
public class CQrDecode {

    static {
        /*
            dll 问题
            IDEA中通过load加载
            或者配置loadLibrary，都是要配置 -Djava.library.path=D:\work\priusis\projects\ower\QrDecode
         */
        try {
            String path = parseAbsolutePath("/qr/dll", "/qr/dll");
            log.debug("load加载path:{}", path);
            if (Platform.isWindows()) {
                System.load(path + "/QrDecode.dll");
            } else if (Platform.isLinux()) {
                String lib = System.getProperty("java.library.path");
                lib = path + ":" + lib;
                log.debug("load加载 java.library.path:{}", lib);
                System.setProperty("java.library.path", lib);
                System.loadLibrary("QrDecode");
            }
        } catch (Exception e) {
            log.error("loadLibrary Exception");
        }
    }

    public native int hello(String str);

    public native int ZOOYAPI_GetCode(String path, String qrString, int[] result);

    public native int ZOOYAPI_GetCodeII(String path, String qrString, int[] result);

    /**
     * @param relatePath 相对路径 /qr/dat/
     * @return
     */
    public static String parseAbsolutePath(String relatePath, String defaultPath) {
        String path = defaultPath;

        if (Platform.isWindows()) {
            path = CQrDecode.class.getResource(relatePath).getPath();
            path = path.replaceFirst("/", "");//排除中文空格
            path = path.replaceAll("%20", " ");//排除中文空格
            path = path.replaceAll("/", "\\\\");//排除中文空格
            try {
                path = java.net.URLDecoder.decode(path, "utf-8"); //解决路径包含中文的情况
            } catch (UnsupportedEncodingException e) {
                log.error("巡检二维码异常", e);
            }
        }
        if (Platform.isLinux()) {
            try {
                ApplicationHome h = new ApplicationHome(CQrDecode.class);
                File jarF = h.getSource();
                log.debug("load加载jarF:{}", jarF);
                log.debug("load加载jarF:{}", jarF.getPath());
                path = jarF.getParentFile().toString() + relatePath;
            } catch (Exception e) {
                log.error("巡检二维码获取path异常：{}", e);
                path = "/app/smart-property/qr/dll";
            }
        }

        return path;
    }
}
