package com.redrield.chocotest;

import org.bukkit.Location;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.plugin.java.JavaPlugin;

import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;

public final class ChocoTest extends JavaPlugin {

    private native void nativeOnEnable();
    private native void nativeOnDisable();
    private native void teleport(Player p, Location loc);

    @Override
    public void onEnable() {
        String os = System.getProperty("os.name").toLowerCase();
        getDataFolder().mkdirs();
        getServer().getPluginManager().registerEvents(new Events(), this);
        try {
            if (os.contains("win")) {
                linkWindows();
            } else if (os.contains("nix") || os.contains("nux") || os.contains("aix")) {
                linkUnix();
            }
        }catch(IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onDisable() {
    }

    private void linkWindows() throws IOException {
        File dll = new File(getDataFolder(), "ChocoTest.dll");
        if(!dll.exists()) {
            dll.createNewFile();
            InputStream in = this.getClass().getResourceAsStream("/ChocoTest.dll");
            OutputStream out = new FileOutputStream(dll);
            int bufSize = 1024;
            byte buf[] = new byte[bufSize];
            int len;
            while((len = in.read(buf)) > 0) {
                out.write(buf, 0, len);
            }
            in.close();
            out.close();
        }
        System.load(dll.getAbsolutePath());
    }

    private void linkUnix() throws IOException {
        File so = new File(getDataFolder(), "ChocoTest.so");
        if(!so.exists()) {
            FileWriter wr = new FileWriter(so);
            InputStreamReader in = new InputStreamReader(this.getClass().getResourceAsStream("ChocoTest.so"));
            int i;
            while((i = in.read()) != -1) {
                wr.write(i);
            }
        }
        System.load(so.getAbsolutePath());
    }

    public native boolean onCommand(CommandSender cs, Command cmd, String label, String[] args);
}