package antsim.start;

import java.io.IOException;
import java.util.concurrent.atomic.AtomicBoolean;

import antsim.entity.EntityNestEntrance;
import antsim.init.Entities;
import antsim.nest.Nest;
import antsim.worker.WorkerComType;
import antsim.worker.WorkerServer;
import antsim.worker.WorkerSocket;
import antsim.world.World;
import bdf.types.BdfArray;
import bdf.types.BdfNamedList;
import bdf.types.BdfObject;
import bdf.types.BdfReader;
import gl_engine.MathHelpers;
import gl_engine.vec.Vec2d;
import mainloop.manager.MainloopManager;
import mainloop.task.IMainloopTask;

public class StartServer implements IMainloopTask
{
	private static WorkerServer server;
	private static AtomicBoolean needToUpdate = new AtomicBoolean();
	
	public static void main(String[] args) throws IOException, InterruptedException
	{
		MathHelpers.init();
		Entities.init();
		
		Start.isServer = true;
		
		int port = Start.DEFAULT_PORT;
		
		if(args.length > 0) {
			port = Integer.parseInt(args[0]);
		}
		
		server = new WorkerServer(port);
		server.start();
		
		Start.mainloop = new MainloopManager(Start.START);
		Start.mainloop.register(new StartServer());
		Start.mainloop.register(Start.START);
		
		for(int i=0;i<2;i++)
		{
			Nest nest = new Nest(i);
			Vec2d area_pos = new Vec2d(Math.random() * 50 - 25, Math.random() * 50 - 25);
			
			for(int j=0;j<50;j++)
			{
				World.WORLD.nests.add(nest);
				World.WORLD.entities.add(new EntityNestEntrance(
						nest, area_pos.add(new Vec2d(Math.random() * 20 - 10, Math.random() * 20 - 10))));
			}
		}
		
		Start.mainloop.start();
		
		server.close();
	}
	
	public static void markNeedToUpdate() {
		needToUpdate.set(true);
	}

	@Override
	public boolean MainLoopDelay(long millis) {
		return millis > 10;
	}

	@Override
	public boolean MainLoopRepeat() {
		return true;
	}

	@Override
	public void MainLoopUpdate()
	{
		server.update();
		
		if(needToUpdate.getAndSet(false))
		{
			BdfReader reader = new BdfReader();
			BdfObject bdf = reader.getObject();
			BdfNamedList nl = bdf.getNamedList();
			
			nl.set("type", bdf.newObject().setAutoInt(WorkerComType.UPDATE));
			
			World.WORLD.saveBDF(bdf);
			
			server.broadcast(reader);
		}
	}
}