package client;

import java.awt.Frame;
import java.io.EOFException;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;

import javax.swing.JOptionPane;

public class ClientTh extends Thread {
	
	private Socket connection;
	private Client control;
	private ObjectInputStream input;
	private ObjectOutputStream output;
	private String message = "";
	private String username = "";
	private Secret test[];
	private String secTo[ ];
	private int pointer = 0;
	private int secretMax = 3;
	public int v_port = 1000;
	public int a_port = v_port + 1000;
//	public int port;
	boolean single = true;
	public AVReceive receiver;
	
	public ClientTh(  Socket s, Client c, String n )
	{
		connection = s;
		control = c;
		username = n;
		test = new Secret[ secretMax ];
		secTo = new String [ secretMax ];
		for( int i = 0; i < secretMax; i++ )
			secTo[ i ] = "0";
		
		try{
			output = new ObjectOutputStream( connection.getOutputStream());
			output.flush();
			input = new ObjectInputStream( connection.getInputStream());
			
			output.writeObject(username);
			message = (String) input.readObject();
			while( message.charAt(0) == 'I' )
			{
				username = JOptionPane.showInputDialog(new Frame(), "線上已有同名使用者，請更換ID：");
				output.writeObject(username);
				message = (String) input.readObject();
			}
			control.showText( message ,null );
		}
		catch( IOException e ){
			e.printStackTrace();
			System.exit(1);
		}
		catch( ClassNotFoundException cnfex ){
			control.showText("\nUnknown username",null);
		}
	}
	
	public void write( String s )
	{
		message = s;
		try{
			output.writeObject( message );
			output.flush();
		}catch( IOException e ){
			e.printStackTrace();
			System.exit(1);
		}
	}
	
	// 主動開啟悄悄話
	public void set( String sendTo, String name )
	{
		int space = -1;
		for( int i = 0; i < secretMax; i++ )
		{
			if( secTo[i] == "0" )
				if( space == -1 )
					space = i;
		}
		if( space == -1 )
		{
			control.showText( "\n您的悄悄話視窗數目已達上限" ,null);
		}
		else
		{
			test[ space ] = new Secret( this, sendTo, name );
			test[ space ].setVisible( true );
			secTo[ space ] = sendTo;			
			pointer++;
		}
	}

	// 關閉悄悄話視窗
	public void close( String sendTo )
	{
		for( int i = 0; i < pointer; i++ )
		{
		    if( secTo[i].equals( sendTo ) )
		    {
		    	test[i].setVisible( false );
		    	secTo[i] = "0";
		    	break;
		    }
		}
	}
	
	public void close()
	{
		for( int i = 0; i < secretMax; i++ )
			if( secTo[i] != "0" )
				test[i].setVisible(false);
	}
	
	public void recFile( String s )
	{
		ReceiveFile receiver = new ReceiveFile( s, control.host, control );
		receiver.start();
	}
	
	public void run()
	{
		try {
			char type;
			char success;
			do {
				message = (String) input.readObject();

				type = message.charAt(0);
				success = message.charAt(1);
				message = message.substring(1);
				
				if ( type == '-' )
				{
					output.writeObject( "-1" );
					break;
				}
					
				switch ( type ) {
				case '0':
//					control.showText( "\n" + message , null);
					control.show_received_Text( message );
					break;
				case '1':
					control.list.setText( message );
					break;
				case '2': // 收到悄悄話訊息
					if( success == '1' )
						control.showText( "\n對方的悄悄話視窗已達上限，無法收到您傳的訊息",null);
					else
					{
						message = message.substring(1);
						String send = message.substring( 0, message.indexOf( ">" ));
    					int i = -1;
	     				boolean found = false;
		    			if( pointer == 0 )
			    		{
		    				i = 0;
				    		test[i] = new Secret( this, send, username );
					    	secTo[i] = send;
   		    				test[i].setVisible( true );
			    			pointer++;
				    	}
					    else
    					{
	    				    for( int j = 0; j < pointer; j ++ )
		    			    {
			    			    if( secTo[j].equals( send ) )
    			    			{
	     			    			i = j;
		    			    		found = true;
    			    				break;
	    			    		}
		    			    }
    		    			if( found == false )
	    		    		{
		    		    		for( int j = 0; j < secretMax; j++ )
			    		    	{
				    		    	if( secTo[j] == "0" )
    					    		{
	    			    				i = j;
		    		    				test[i] = new Secret( this, send, username );
		        						secTo[i] = send;
		    	    					test[i].setVisible( true );
		    		    				if( i >= pointer )
		    			    				pointer++;
							        	break;
    							    }
    	    					}
	    	    			}
		    			}
    		    		if( i != -1 )
    			    	{
    				    	test[i].show( message );
        				}
        				else
    	    			{
    		    			write( "2" + send + "\n1" );
    			    		control.showText( "\n" + send + "傳了個訊息給您，但您的悄悄話視窗數目已達上限故無法顯示",null );
    				    }
					}
					break;
				case '3':
					if ( message.charAt(0) == '1' )
						control.room.addItem( message.substring(1) );
					//		control.showText("\n新聊天室建立：" + message.substring(1) );
					break;
				case '4':
					if ( message.charAt(0) == '1' ) {
						control.showText("\n" + message.substring(1), null);
						control.setEndSelection();
					}
					break;
				case '5':
					control.listUsers( message ); // ComboBox選單
					break;
				case '6'://sendfile
					control.showText( "\n正在接收檔案：" + message + "\n", null );
					control.setEndSelection();
					recFile( message );
					break;
				case '7':	//send video, 70:failed, 71:success, 72:接收
					if( message.charAt(0) == '0' )
					{
						control.showText("\n對方不接受視訊傳輸！\n", null );
					}
					else if( message.charAt(0) == '1' )
					{
						String ip = message.substring(1);
						control.showText("\n對方ip:" + ip + "\n", null );
//						control.mediaSender = new MediaSender(
//								ip, String.valueOf( portCount ));
//						ip = "140.112.18.209";
						control.mediaSender.set( ip, String.valueOf( v_port ));
						control.showText( "port" + v_port, null );
						control.mediaSender.run();
						v_port += 4;
						a_port = v_port + 1000;
					}
					else if( message.charAt(0) == '2' )
					{
						String copy = new String(message.substring(1));
						String name = message.substring(1, message.indexOf('\n'));
			
						String temp = name + "傳送視訊給你，要接受嗎？";
						int choice = JOptionPane.showConfirmDialog( control, temp,
								"確認", JOptionPane.YES_NO_OPTION );
						if( choice != JOptionPane.YES_OPTION )
							write( "70" + 
								message.substring( 1, message.indexOf('\n') ));
						else
						{
							System.out.println( "NAME: " + name );
							write( "71" + name );
							System.out.println( "MSG: " + copy );
							String p = copy.substring( copy.lastIndexOf('\n')+1);
							v_port = Integer.parseInt( p );
							temp = copy.substring(
								copy.indexOf('\n')+1, copy.lastIndexOf('\n'))
								+ "/" + v_port + "/1";
//							String temp2 = copy.substring(
//									copy.indexOf('\n')+1, copy.lastIndexOf('\n'))
//									+ "/" + ( v_port+1000 ) + "/1";
//							temp = "140.112.18.209/1000/1";
//							System.out.println("Temp: " + temp );
							String sess[] = { temp };
							v_port += 4;
							a_port = v_port + 1000;
							AVReceive ar = new AVReceive( sess, 0 );
							ar.start();
						}
					}
					break;
				case '8':	//send audio, 80:failed, 81:success, 82:接收
					if( message.charAt(0) == '0' )
					{
						control.showText("\n對方不接受音訊傳輸！\n", null );
					}
					else if( message.charAt(0) == '1' )
					{
						String ip = message.substring(1);
						control.showText("\n對方ip:" + ip, null );
//						ip = "140.112.18.209";
						control.audioSender.set( ip, String.valueOf( a_port ) );
						control.showText( "port" + a_port, null );
						control.audioSender.run();
						a_port += 2;
//						v_port = a_port - 1000;
					}
					else if( message.charAt(0) == '2' )
					{
						String copy = new String(message.substring(1));
						String name = message.substring(1, message.indexOf('\n'));
			
						String temp = name + "傳送音訊給你，要接受嗎？";
						int choice = JOptionPane.showConfirmDialog( control, temp,
								"確認", JOptionPane.YES_NO_OPTION );
						if( choice != JOptionPane.YES_OPTION )
							write( "80" + 
								message.substring( 1, message.indexOf('\n') ));
						else
						{
							System.out.println( "NAME: " + name );
							write( "81" + name );
							System.out.println( "MSG: " + copy );
							String p = copy.substring( copy.lastIndexOf('\n')+1);
							temp = copy.substring(
								copy.indexOf('\n')+1, copy.lastIndexOf('\n'))
								+ "/" + p + "/1";
//							temp = "140.112.18.209/1000/1";
							a_port = Integer.parseInt( p ) + 2;
							System.out.println("Temp: " + temp );
							String sess[] = { temp };
							AVReceive ar = new AVReceive( sess, 1 );
							ar.start();
						}
					}
					break;
				case '9':	//send movie, 90:failed, 91:success, 92:接收
					if( message.charAt(0) == '0' )
					{
						control.showText("\n對方不接受視訊傳輸！\n", null );
					}
					else if( message.charAt(0) == '1' )
					{
						String ip = message.substring(1);
						control.showText("\n對方ip:" + ip + "\n", null );
//						control.mediaSender = new MediaSender(
//								ip, String.valueOf( portCount ));
						control.movieSender.set( ip, String.valueOf( v_port ));
						control.showText( "port" + v_port, null );
						control.movieSender.run();
						v_port += 4;
					}
					else if( message.charAt(0) == '2' )
					{
						String copy = new String(message.substring(1));
						String name = message.substring(1, message.indexOf('\n'));
			
						String temp = name + "傳送影片給你，要接受嗎？";
						int choice = JOptionPane.showConfirmDialog( control, temp,
								"確認", JOptionPane.YES_NO_OPTION );
						if( choice != JOptionPane.YES_OPTION )
							write( "90" + 
								message.substring( 1, message.indexOf('\n') ));
						else
						{
							System.out.println( "NAME: " + name );
							write( "91" + name );
							System.out.println( "MSG: " + copy );
							String p = copy.substring( copy.lastIndexOf('\n')+1);
							temp = copy.substring(
								copy.indexOf('\n')+1, copy.lastIndexOf('\n'))
								+ "/" + p + "/1";
							v_port = Integer.parseInt( p ) + 4;
//							System.out.println("Temp: " + temp );
//							String sess1[] = { temp };
							int port = Integer.parseInt( p );
							p = String.valueOf( port+2 );
							String temp2 = copy.substring(
									copy.indexOf('\n')+1, copy.lastIndexOf('\n'))
									+ "/" + p + "/1";
							String sess[] = { temp, temp2 };
							AVReceive ar = new AVReceive( sess, 2 );
							ar.start();
						}
					}
					break;
				default:
					break;
				}
			} while( true );

			control.showText( "\nClosing connection.\n" ,null);
			output.close();
			input.close();
			connection.close();
			control.isActive = false;
		} catch ( EOFException eof ) {
			System.out.println( "Server terminated connection" );
		} catch ( IOException io ) {
			io.printStackTrace();
		} 
		catch ( ClassNotFoundException cnfex ) {
			message = "\nUnknown object type received";
		}
	}	
}
