package transporte;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Vector;
import aplicacao.Usuario;

public class ClienteLogin extends Thread{
	private Socket socketClienteServidor;
	private DataOutputStream toServidor;
	private BufferedReader fromServidor;
	private Cliente cliente;
	private Vector<Usuario> usuarios;
	
	public ClienteLogin(Cliente cliente,String login, String senha){
		this.cliente = cliente;
		//ESTABELECENDO CONEXAO COM O SERVIDOR DE LOGIN
		try{
			String retorno;
			this.socketClienteServidor = new Socket("G4C34",2000);
			this.toServidor = new DataOutputStream(this.socketClienteServidor.getOutputStream());
			this.fromServidor = new BufferedReader(new InputStreamReader(this.socketClienteServidor.getInputStream()));
			this.toServidor.writeBytes("conectar\n");
			
			this.toServidor.writeBytes(login+"\n");
			this.toServidor.writeBytes(senha+"\n");
			retorno = this.fromServidor.readLine();
			if(retorno.equalsIgnoreCase("conectado")){
				this.usuarios = new Vector<Usuario>();
				this.cliente.setConectado(true);
			}else{
				this.cliente.setConectado(false);
			}
		}catch(Exception e){
			System.out.println("não foi possivel conectar com o servidor!");
		}
	}
	public void run(){
		while(this.cliente.getConectado()){
			//OBTENDO DO SERVIDOR DE LOGIN OS USUÁRIOS
			try {
				Vector<Usuario> novosUsuarios = new Vector<Usuario>();
				this.toServidor.writeBytes("status\n");
				int numeroDeContatosOnLine = Integer.parseInt(this.fromServidor.readLine());
				for(int i = 0; i < numeroDeContatosOnLine; i++){
					novosUsuarios.add(new Usuario(this.fromServidor.readLine(),
							this.fromServidor.readLine(),
							this.fromServidor.readLine()));
				}
				this.compararUsuarios(novosUsuarios);
				this.usuarios = novosUsuarios;

			} catch (IOException e) {
				try {
					System.out.println("servidor caiu!");
					this.cliente.desconectar();
				} catch (IOException e1) {
					System.out.println("não foi possivel desconectar de outros clientes!");
				}
			}
		}
		//QUANDO O CLIENTE DESCONECTA
		try {
			this.toServidor.writeBytes("sair\n");
			this.toServidor.writeBytes(this.cliente.getLogin()+"\n");
			if(this.fromServidor.readLine().equalsIgnoreCase("desconectado")){
				this.socketClienteServidor.close();
				this.fromServidor.close();
				this.toServidor.close();
				this.cliente.setConectado(false);
			}
		} catch (IOException e) {
			System.out.println("não foi possivel se comunicar com o servidor");
			try {
				this.cliente.desconectar();
			} catch (IOException e1) {
				System.out.println("não foi possivel desconectar de outros clientes!");
			}
		}
		
	}

	private void compararUsuarios(Vector<Usuario> novosUsuarios) throws UnknownHostException, IOException {
		//COMPARANDO OS USUARIOS ANTIGOS COM OS NOVOS
		for(int index = 0; index < this.usuarios.size(); index++){
			int indexNovo = 0;
			boolean igual = false;
			while(indexNovo < novosUsuarios.size() && !igual){
				if(this.usuarios.get(index).getLogin().equalsIgnoreCase(novosUsuarios.get(indexNovo).getLogin())){
					igual = true;
				}else{
					indexNovo++;
				}
			}
			if(!igual){
				this.cliente.desconectarUsuario(this.usuarios.get(index));
			}
		}
		
		
		//COMPARANDOS OS NOVOS USUARIOS COM OS ANTIGOS
		for(int indexNovo = 0; indexNovo < novosUsuarios.size(); indexNovo++){
			int index = 0;
			boolean igual = false;
			while(index < this.usuarios.size() && !igual){
				if(novosUsuarios.get(indexNovo).getLogin().equalsIgnoreCase(this.usuarios.get(index).getLogin())){
					igual = true;
				}else{
					index++;
				}
			}
			if(!igual){
				this.cliente.conectarUsuario(novosUsuarios.get(indexNovo));
			}
		}
	}
	
	public Vector<Usuario> getUsuarios(){
		return this.usuarios;
	}

}
