package ru.yandex.webmaster3.core.jni;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import ru.yandex.webmaster3.core.host.service.HostCanonizer;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.StandardCopyOption;

/**
 * @author leonidrom
 */
@Service
@Slf4j
public class NativeLoader {
    public void init() {
        log.info("Loading JNI libraries");
        try {
            loadLibraries();
        } catch (IOException e) {
            throw new UnsatisfiedLinkError(e.getMessage());
        }
    }

    private static void loadLibraries() throws IOException {
        doLoadLibrary("wmc-canonizer-jni");
        doLoadLibrary("wmc-arcutils-jni");
    }

    private static void doLoadLibrary(String libName) throws IOException{
        log.info("Loading {}", libName);
        try {
            System.loadLibrary(libName);
            log.info("Loaded " + libName + " from file system");
            return;
        } catch (Throwable e) {
            log.info("Error loading from file system, will try jar: " + e.getMessage());
        }

        final String libFileName = System.mapLibraryName(libName);
        final File file;
        try (InputStream in = HostCanonizer.class.getClassLoader().getResourceAsStream(libFileName)) {
            if (in == null) {
                throw new IOException("Missing JNI library - " + libFileName);
            }
            final int pos = libFileName.lastIndexOf('.');
            file = File.createTempFile(libFileName.substring(0, pos), libFileName.substring(pos));
            file.deleteOnExit();
            Files.copy(in, file.toPath(), StandardCopyOption.REPLACE_EXISTING);
        }

        try {
            System.load(file.getAbsolutePath());
        } catch (Throwable e) {
            log.info("Error loading from jar: " + e.getMessage());
            throw e;
        }

        log.info("Loaded " + libName + "from jar");
    }
}
