package net.halbear.Terrain4J.EngineCore.Threads;

import net.halbear.Terrain4J.EngineCore.Logic.EngineConfig;
import net.halbear.Terrain4J.EngineCore.Logic.EngineInstance;
import net.halbear.Terrain4J.EngineCore.Logic.GameLogic;
import net.halbear.Terrain4J.EngineCore.Main.PrimaryRuntime;
import net.halbear.Terrain4J.EngineCore.Profiling.CPUMonitor;
import org.tinylog.Logger;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class MainThread extends EngineThread  {

    @Override
    public void TickEvent(long nsTimeDiff){

    }
    @Override
    public void FrameEvent(long now, long InitialTime){
        gameLogic.Update(PrimaryRuntime.GetEngineInstance(),  (now - InitialTime));
    }
    @Override
    public void CycleEvent(){

    }
    @Override
    public void SecondEvent(){
        EngineConfig.FrameRate_MAINENGINETHREAD = Frames;
        EngineConfig.TPS_MAINENGINETHREAD = TickFrames;
        List<String[]> profiling = new ArrayList<>();
        profiling.addAll(Collections.singleton(CPUMonitor.LogCPUUsage()));
        List<String> Threads = CPUMonitor.GetThreadsInUse();
        String[] ThreadInformation = new String[Math.min(Threads.size() + 3,14)];
        ThreadInformation[0] = "\nTERRAIN4J PROCESS INFORMATION:\n";
        ThreadInformation[1] = String.format("Thread Count: %d \n",Threads.size());
        ThreadInformation[2] = "v Threads In Use v\n";
        for(int i = 0; i < Math.min(Threads.size(),10); i++){
            ThreadInformation[3 + i] = String.format("Thread %d -> %s",i,Threads.get(i));
        }
        if(Threads.size() > 10){
            ThreadInformation[13] = "...";
        }
        profiling.addAll(Collections.singleton(ThreadInformation));
        EngineConfig.getInstance().SetSystemProfiling(profiling);
        gameLogic.SecondUpdate(PrimaryRuntime.GetEngineInstance());

    }
    public void UpdateTickRateThreshold(){
        CappedToTickRate = EngineConfig.getInstance().GetMainTickCap();
        TickRate = EngineConfig.getInstance().GetMainTickrate();
        if (CappedToTickRate){
            TickThreshold = (double) 1000000000 / (double) TickRate;
        } else{
            TickThreshold = 0;
        }
    }
    public MainThread(EngineInstance engineInstance, GameLogic appLogic){
        super(engineInstance, appLogic, "Main");
        UpdateTickRateThreshold();
    }

}
