package electrosphere.test.testutils;

import java.util.concurrent.TimeUnit;

import org.junit.jupiter.api.Assertions;

import electrosphere.engine.Globals;
import electrosphere.engine.Main;
import electrosphere.engine.loadingthreads.LoadingThread;
import electrosphere.engine.loadingthreads.LoadingThread.LoadingThreadType;
import electrosphere.engine.profiler.Profiler;
import electrosphere.net.NetUtils;

public class EngineInit {

    //The maximum number of frames to wait before failing the startup routine
    public static final int MAX_FRAMES_TO_WAIT = 100;

    /**
     * Max time in milliseconds to wait while flushing
     */
    public static final int MAX_TIME_TO_WAIT = 15000;

    /**
     * Initializes the engine
     */
    public static void initHeadlessEngine(){
        Globals.RUN_CLIENT = true;
        Globals.RUN_SERVER = true;
        Globals.RUN_AUDIO = false;
        Globals.HEADLESS = true;
        Profiler.PROFILE = false;
        NetUtils.setPort(0);
        Main.startUp();
    }

    /**
     * Initializes the engine
     */
    public static void initGraphicalEngine(){
        Globals.RUN_CLIENT = true;
        Globals.RUN_SERVER = true;
        Globals.RUN_AUDIO = false;
        Globals.RUN_SCRIPTS = false;
        Globals.HEADLESS = false;
        Profiler.PROFILE = false;
        NetUtils.setPort(0);
        Main.startUp();
    }
    
    /**
     * Setups up a locally-connected client and server that have loaded a test scene
     */
    public static void setupConnectedTestScene(){
        //
        //load the scene
        LoadingThread loadingThread = new LoadingThread(LoadingThreadType.LEVEL,"testscene1");
        Globals.threadManager.start(loadingThread);

        //
        //wait for client to be fully init'd
        int frames = 0;
        while(Globals.threadManager.isLoading()){
            TestEngineUtils.simulateFrames(1);
            try {
                TimeUnit.MILLISECONDS.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            frames++;
            if(frames > MAX_FRAMES_TO_WAIT){
                String errorMessage = "Failed to setup connected test scene!\n" +
                "Still running threads are:\n"
                ;
                for(LoadingThread thread : Globals.threadManager.getLoadingThreads()){
                    errorMessage = errorMessage + thread.getType() + "\n";
                }
                Assertions.fail("Failed to startup");
            }
        }
    }

    /**
     * Setups up a locally-connected client and server that have loaded the viewport
     */
    public static void setupConnectedTestViewport(){
        //
        //load the scene
        LoadingThread loadingThread = new LoadingThread(LoadingThreadType.LOAD_VIEWPORT);
        Globals.threadManager.start(loadingThread);

        TestEngineUtils.flush();
    }

}
