package Multi;

import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;

import main.Jeu;

import org.newdawn.slick.Color;
import org.newdawn.slick.Graphics;
import org.newdawn.slick.Input;
import org.newdawn.slick.SlickException;

import personnage.Personnage;
import world.DrawMap;
import world.SaveAndLoadMap;
import boxs.WorldBoxsServer;

public class Serveur extends Thread
{
	Socket client;
	
	Personnage gentil, mechant;

	public static WorldBoxsServer boxs;

	public static int[][] map;
	PacketPersoClient pack;
	PacketPersoServer PackGentil, PackMechant;
	boolean fire;
	public Serveur() throws SlickException
	{
		gentil = new Personnage(0);
		mechant = new Personnage(1);
		map = SaveAndLoadMap.Load();
		boxs = new WorldBoxsServer();
		pack = new PacketPersoClient();
		PackGentil = new PacketPersoServer();
		PackMechant = new PacketPersoServer();
	}
	
	public void run()
	{
		try {
			ServerSocket server = new ServerSocket(23);

			System.out.print("connect on ");
			System.out.println(InetAddress.getLocalHost());
			
			client = server.accept();
			Multi.state = "jeu";
			ObjectInputStream reader = new ObjectInputStream(client
					.getInputStream());
			ObjectOutputStream writer = new ObjectOutputStream(client
					.getOutputStream());
			
			writer.writeObject(map);
			while ((pack = (PacketPersoClient) reader.readObject()) != null) 
			{
				mechant.set(pack);
				PackGentil.set(gentil, fire);
				writer.writeObject(PackGentil);
				PackMechant.set(mechant, false);
				writer.writeObject(PackMechant);
			}
			
			reader.close();
			writer.close();
			client.close();
			server.close();
			Multi.state = "menu";
			Jeu.state = "menu";
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public String getOwner()
	{
		return client.getInetAddress().getHostAddress();
	}
	
	public void draw(Graphics g)
	{
		g.setColor(Color.gray);
		g.fillRect(0, 0, 800, 640);
		DrawMap.draw(g, map);
		gentil.draw(g);
		mechant.draw(g);
		boxs.draw(g);
	}
	
	public void update(Input in) throws SlickException
	{
		 if(in.isKeyDown(Input.KEY_F))
			 gentil.move(1);
		 if(in.isKeyDown(Input.KEY_S))
			 gentil.move(0);
		 if(in.isKeyPressed(Input.KEY_E))
			 gentil.jump();
		 if(gentil.fireSpeed == 4)
		 {
			 if(in.isKeyPressed(Input.KEY_SPACE) && gentil.timeSinceLastFire >= 4)
			 {
				 gentil.tirer();
				 fire = true;
			 }
		 }
		 else if(in.isKeyDown(Input.KEY_SPACE))
		 {
			if(gentil.timeSinceLastFire >= gentil.fireSpeed)
			{
				gentil.tirer();
				fire = true;
				gentil.timeSinceLastFire = 0;
			}
		 }
		 
		 gentil.timeSinceLastFire++;	 
		 
		 gentil.testBalle(mechant.balles);
		 mechant.testBalle(gentil.balles);
		
		 gentil.update();
		 mechant.update();
		 
		 if(mechant.testMort())
		 {
			 mechant.resetAll();
			 gentil.score++;
		 }
		 
		 if(gentil.testMort())
		 {
			 gentil.resetAll();
			 mechant.score++;
		 }
		 
		 boxs.update();
	}
}
