package com.ygames.ysoccer.screens;

import com.badlogic.gdx.Gdx;

import java.io.File;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

class OnlineServerProcess {

    private static Process process;

    static {
        Runtime.getRuntime().addShutdownHook(new Thread(OnlineServerProcess::stop));
    }

    static synchronized boolean isRunning() {
        return process != null && process.isAlive();
    }

    static synchronized void start() throws IOException {
        if (isRunning()) {
            return;
        }

        File script = internalScript("launch-ysoccer-server-only.sh");
        ProcessBuilder processBuilder = new ProcessBuilder(script.getAbsolutePath());
        processBuilder.directory(yspBase());
        processBuilder.environment().put("YSOCCER_HIDE_PORT_HINT", "1");
        process = processBuilder.start();
    }

    static synchronized void stop() {
        if (!isRunning()) {
            return;
        }

        process.destroy();
        try {
            if (!process.waitFor(2, TimeUnit.SECONDS)) {
                process.destroyForcibly();
                process.waitFor();
            }
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
        process = null;
    }

    private static File internalScript(String name) {
        String internalDir = System.getProperty("ysoccer.internalDir");
        if (internalDir != null && internalDir.trim().length() > 0) {
            return new File(internalDir, name);
        }
        return new File(Gdx.files.local(".internal/" + name).file().getAbsolutePath());
    }

    private static File yspBase() {
        String base = System.getProperty("ysoccer.yspBase");
        if (base != null && base.trim().length() > 0) {
            return new File(base);
        }
        File cwd = Gdx.files.local(".").file();
        File parent = cwd.getParentFile();
        if (parent != null) {
            parent = parent.getParentFile();
        }
        return parent != null ? parent : cwd;
    }
}
