package Multi;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.net.UnknownHostException;

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.WorldBoxsClient;

public class Client extends Thread
{
	Socket s;
	public static int[][] map;
	Personnage gentil, mechant; // Client == mechant
	boolean connected = false;
	public static WorldBoxsClient boxs;

	private ObjectOutputStream writer;
	private ObjectInputStream reader;
	PacketPersoClient nextpack;
	PacketPersoServer pack;
	Client() throws SlickException
	{
		gentil = new Personnage(0);
		mechant = new Personnage(1);
		map = SaveAndLoadMap.Load();
		boxs = new WorldBoxsClient();
		pack = new PacketPersoServer();
		nextpack = new PacketPersoClient();
	}
	public void run()
	{
		if(connected)
		{
			try {
				map = (int[][]) reader.readObject();
				writer.writeObject((PacketPersoClient) nextpack);
				while ((pack = (PacketPersoServer) reader.readObject()) != null) 
				{
					writer.writeObject(nextpack);
					if(pack.id == true)
						gentil.set(pack);
					else
						mechant.set(pack);
				}
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} 
			
			try {
				reader.close();

				writer.close();
				s.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			Multi.state = "menu";
			Jeu.state = "menu";
		}
	}
	public void connect(String ip) throws UnknownHostException, IOException
	{
		s = new Socket(ip, 23);
		writer = new ObjectOutputStream(s.getOutputStream());
		reader = new ObjectInputStream(s.getInputStream());
		connected = true;
	}
	public void update(Input in) throws SlickException
	{
		 boolean fire = false;
		 
		 if(in.isKeyDown(Input.KEY_RIGHT))
			 mechant.move(1);
		 if(in.isKeyDown(Input.KEY_LEFT))
			 mechant.move(0);
		 if(in.isKeyPressed(Input.KEY_UP))
			 mechant.jump();
		 if(mechant.fireSpeed == 4)
		 {
			 if(in.isKeyPressed(Input.KEY_ENTER) && mechant.timeSinceLastFire >= 4)
			 {
				 mechant.tirer();
				 fire = true;
			 }
		 }
		 else if(in.isKeyDown(Input.KEY_SPACE))
		 {
			if(mechant.timeSinceLastFire >= mechant.fireSpeed)
			{
				mechant.tirer();
				fire = true;
				mechant.timeSinceLastFire = 0;
			}
		 }
		 mechant.timeSinceLastFire++;
		 
		 boxs.update();
		 nextpack.set(mechant, fire);
	}
	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);
	}
}
