package client;

import java.io.*;
import java.net.*;
import java.util.*;
import java.awt.*;
import java.awt.event.*;

import javax.swing.*;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.DefaultStyledDocument;
import javax.swing.text.SimpleAttributeSet;
import javax.swing.text.StyleConstants;
import javax.swing.text.StyleContext;

//這份的基本架構是參照我用的書的21章，一樣的部分就不再說明了
//這份的作法是一開client就去連線
//目前切換聊天室時，server端會出問題，member list無法正確顯示，
//尚在研究中，其他部分都好了，先用吧~ ^^

//-1:terminate 0:聊天內容 1:聊天室成員 2:悄悄話 3:建新room 4:換room 5:全部成員名單
//6:傳送檔案 7:傳送視訊 8:傳送聲音
public class Client extends JFrame // implements ActionListener
{
	
	Chooser_Font choosefont = new Chooser_Font();

	boolean ob = false;

	public int colornumber = 0;

	public int fontnumber = 49;

	public int fontsizenumber = 4;

	public int fontstylenumber = 0;

//	String ID = "140.112.18.208";
	public String host;

	//setting display's parameter
	SimpleAttributeSet sas = new SimpleAttributeSet();

	SimpleAttributeSet sas_received = new SimpleAttributeSet();

	StyleContext sc = new StyleContext();

	DefaultStyledDocument dse = new DefaultStyledDocument(sc);

	Font font = null;

	//==============set for graph class==================
	Graph g = new Graph();

	//=============================

	public JTextField enter;

	public JTextPane display = new JTextPane();

	//	private JTextArea display;

	private JButton stop; //斷線用，但後來我加了關window也會斷，所以這個鈕可以拿掉

	public JTextArea list; //顯示聊天室成員名單（目前設計是看不到所有client）

	public JComboBox room;

	private String roomName[] = new String[1];

	private JButton newRoom;

	//	private JButton delRoom;
	private JPanel right;

	private String username;

	private String message = "";

	///////////////////////////////
	private JButton fontButton;

	private JButton fontsize;

	private JButton send;

	//	private JButton figure;
	private JButton figure;

	private JLabel listtitle;

	private JPanel panel;

	private JMenu[] menu;

	private String menuname[] = { "檔案(F)", "執行(A)", "說明(H)" };

	private JMenuItem jmenuitem1[] = new JMenuItem[4];

	private JMenuItem jmenuitem3[] = new JMenuItem[6];

	private JMenuItem jmenuitem4 = new JMenuItem();

	private String itemname1[] = { "登入(I)", "登出(O)", "關閉(C)" };

	private String itemname3[] =
		{"建立新聊天室(S)", "傳送檔案(F)", "傳送視訊(V)", "傳送聲音(A)",
		 "播放影片(M)", "播放音樂(W)"};

	private String itemname4 = "版本(A)";

	private JRadioButtonMenuItem mystateitem[];

	private JButton start;

	private JLabel image;

	//悄悄話
	private JComboBox listTalk; //送悄悄話用list

	private JButton sendSecret;

	/////state設定
	private JMenu statemenu;

//	private String mystatename[] = { "線上", "離開", "顯示為離線" };

	private ButtonGroup mystategroup;

	private GridBagLayout layout;

	private GridBagConstraints constraints;

	private Container c;

	/////////////////////////////

	private int temp = 0; //修正ComboBox連選問題

	private ClientTh thread;

	public boolean isActive = false;
	
	public VideoSender mediaSender;
	public AudioSender audioSender;
	public MovieSender movieSender;


	public Client( String hostname ) {
		super("Client");

		host = hostname;
		
		setUndecorated(true);
		getRootPane().setWindowDecorationStyle(JRootPane.FRAME);

		///////////////
		c = getContentPane();
		//////////////////////////////choose_font
		// actionevent////////////////////
		choosefont.colorcomboBox.addItemListener(new ItemListener() {
			public void itemStateChanged(ItemEvent e) {
				if (e.getStateChange() == ItemEvent.SELECTED) {
					choosefont.fontcolor = choosefont.colorsetting[choosefont.colorcomboBox
							.getSelectedIndex()];
					choosefont.Sample.setForeground(choosefont.fontcolor);
					colornumber = choosefont.colorcomboBox.getSelectedIndex();
					showSample();
				}
			}
		});

		choosefont.FontList.jl
				.addListSelectionListener(new ListSelectionListener() {
					public void valueChanged(ListSelectionEvent e) {
						choosefont.FontList.jt
								.setText((String) choosefont.FontList.jl
										.getSelectedValue());
						choosefont.FontList.si = (String) choosefont.FontList.jl
								.getSelectedValue();
						fontnumber = choosefont.FontList.jl.getSelectedIndex();
						showSample();
					}
				});
		choosefont.StyleList.jl
				.addListSelectionListener(new ListSelectionListener() {
					public void valueChanged(ListSelectionEvent e) {
						choosefont.StyleList.jt
								.setText((String) choosefont.StyleList.jl
										.getSelectedValue());
						choosefont.StyleList.si = (String) choosefont.StyleList.jl
								.getSelectedValue();
						fontstylenumber = choosefont.StyleList.jl
								.getSelectedIndex();
						showSample();
					}
				});
		choosefont.SizeList.jl
				.addListSelectionListener(new ListSelectionListener() {
					public void valueChanged(ListSelectionEvent e) {
						choosefont.SizeList.jt
								.setText((String) choosefont.SizeList.jl
										.getSelectedValue());
						choosefont.SizeList.si = (String) choosefont.SizeList.jl
								.getSelectedValue();
						fontsizenumber = choosefont.SizeList.jl
								.getSelectedIndex();
						showSample();
					}
				});
		choosefont.SizeList.jl.setSelectedIndex(4);
		choosefont.ok.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				choosefont.setVisible(false);
				ob = true;
				setAttribute(choosefont.Sample);
			}
		});
		choosefont.ca.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				choosefont.setVisible(false);
				//	ob = false;
			}
		});

		//////////////////////////////choose_font////////////////////
		/////////////////////////////////////
	
		
		
		////////////////////////
		JMenuBar bar = new JMenuBar();
		menu = new JMenu[menuname.length];
		statemenu = new JMenu("我的狀態(M)");
		for (int i = 0; i < menu.length; i++) {
			menu[i] = new JMenu(menuname[i]);
			menu[i].setMnemonic(menuname[i].split("\\(")[1].charAt(0));
			bar.add(menu[i]);
		}
		ItemHander h = new ItemHander();
		for (int i = 0; i < itemname1.length; i++) {
			jmenuitem1[i] = new JMenuItem(itemname1[i]);
			jmenuitem1[i].setMnemonic(itemname1[i].split("\\(")[1].charAt(0));
			jmenuitem1[i].addActionListener(h);
			if (i == 2) {
//				menu[0].add(statemenu);
				menu[0].addSeparator();
			}
			menu[0].add(jmenuitem1[i]);
		}
		jmenuitem1[1].setEnabled(false);
		jmenuitem1[2].setEnabled(false);
		for (int i = 0; i < itemname3.length; i++) {
			jmenuitem3[i] = new JMenuItem(itemname3[i]);
			jmenuitem3[i].setMnemonic(itemname3[i].split("\\(")[1].charAt(0));
			jmenuitem3[i].addActionListener(h);
			menu[1].add(jmenuitem3[i]);
		}
		jmenuitem3[0].setEnabled(false);
		jmenuitem3[1].setEnabled(false);
		jmenuitem3[2].setEnabled(false);
		jmenuitem3[3].setEnabled(false);
		jmenuitem3[4].setEnabled(false);
		jmenuitem3[5].setEnabled(false);
		
		jmenuitem4 = new JMenuItem(itemname4);
		jmenuitem4.setMnemonic(itemname4.split("\\(")[1].charAt(0));
		jmenuitem4.addActionListener(h);

		menu[2].add(jmenuitem4);

		//state
//		mystateitem = new JRadioButtonMenuItem[mystatename.length];
		mystategroup = new ButtonGroup();

//		for (int i = 0; i < mystatename.length; i++) {
//			if (i == 0)
//				mystateitem[i] = new JRadioButtonMenuItem(mystatename[i],
//						online);
//			else if (i == 1)
//				mystateitem[i] = new JRadioButtonMenuItem(mystatename[i],
//						offline);
//			else
//				mystateitem[i] = new JRadioButtonMenuItem(mystatename[i], bye);
//			statemenu.add(mystateitem[i]);
//			mystategroup.add(mystateitem[i]);
//			mystateitem[i].addActionListener(h);
//		}
//		mystateitem[0].setSelected(true);
		c.add(bar, BorderLayout.NORTH);

		//////////////////////////menubar////////////////////////////
		layout = new GridBagLayout();
		constraints = new GridBagConstraints();

		panel = new JPanel(layout);
		panel.setBorder(BorderFactory.createTitledBorder("chat room"));

		//==========display setting========================================
		display.setDocument(dse);
		display.setEditable(false);

		//==================================================
		//////////graph///////////////////////////////
		buttonaction action = new buttonaction();
		for (int i = 0; i < 36; i++)
			g.Sbutton[i].addActionListener(action);
		for (int i = 0; i < 16; i++)
			g.Dbutton[i].addActionListener(action);
		for (int i = 0; i < 18; i++)
			g.Cbutton[i].addActionListener(action);
		g.sure.addActionListener(action);
		g.cancel.addActionListener(action);
		//////////////////////////////////////////////////

		list = new JTextArea( "", 5, 6 );
		list.setWrapStyleWord(true);
		list.setLineWrap(true);
		//
		fontButton = new JButton("字型");
		fontButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				choosefont.setVisible(true);

			}
		});

		fontsize = new JButton();
		fontsize.setEnabled(false);

		//悄悄話
		listTalk = new JComboBox();
		sendSecret = new JButton( "傳送悄悄話" );
		sendSecret.addActionListener( new ActionListener() {
			public void actionPerformed( ActionEvent e ) {
				if ( ( listTalk.getSelectedItem() != "使用者列表：" )
						&& ( !username.equals( ( String ) listTalk.getSelectedItem()) ) ) {
					thread.set( ( String ) listTalk.getSelectedItem(), username );
				}
			}
		});

		//
		listtitle = new JLabel("聊天室名單");

		send = new JButton("Send");
		send.setBorder(BorderFactory.createRaisedBevelBorder());
		send.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				String send = enter.getText();
				sendData(send);
				StringTokenizer tokens = new StringTokenizer(send, " ");
				showText(username + ">>>", sas);
				while (tokens.hasMoreTokens()) {
					String temp = tokens.nextToken();
					if (match_graph(temp) == false) {
						showText(temp + " ", sas);
					}
				}
				showText("\n", sas);
				enter.setText("");
				display.setSelectionEnd(display.getDocument().getLength());
			}
		});

		enter = new JTextField();

		enter.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {

				String send = e.getActionCommand();
				sendData(send);
				StringTokenizer tokens = new StringTokenizer(send, " ");
				showText(username + ">>>", sas);
				while (tokens.hasMoreTokens()) {
					String temp = tokens.nextToken();
					if (match_graph(temp) == false) {
						showText(temp + " ", sas);
					}
				}
				showText("\n", sas);
				enter.setText("");
				display.setSelectionEnd(display.getDocument().getLength());
			}
		});

		figure = new JButton("figure");
		figure.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {	
				//display graph frame
				g.setVisible(true);				
			}
		});

		image = new JLabel();
	//	image.setText("線上");

		JPanel seperate = new JPanel();
		constraints.fill = GridBagConstraints.BOTH;

		constraints.weightx = 100;
		constraints.weighty = 100;
		addcomponent(new JScrollPane(display), 0, 0, 3, 5);

		constraints.weightx = 100;
		constraints.weighty = 10;
		addcomponent(enter, 0, 6, 3, 1);

		constraints.weightx = 10;
		constraints.weighty = 100;
		addcomponent(new JScrollPane(list), 4, 3, 1, 1);

		constraints.weightx = 0;
		constraints.weighty = 0;
		addcomponent(listTalk, 4, 0, 1, 1);
		addcomponent(sendSecret, 4, 1, 1, 1);
		addcomponent(fontButton, 0, 5, 1, 1);
		addcomponent(figure, 1, 5, 1, 1);

		constraints.weightx = 3;
		constraints.weighty = 3;
		addcomponent(listtitle, 4, 2, 1, 1);
		addcomponent(seperate, 3, 0, 1, 5);
		addcomponent(fontsize, 2, 5, 1, 1);
		addcomponent(image, 4, 4, 1, 1);

		addcomponent(send, 4, 6, 1, 1);

		room = new JComboBox();
		addcomponent(room, 4, 5, 1, 1);
		room.addItemListener(new ItemListener() {
			public void itemStateChanged(ItemEvent e) {
				if (temp != room.getSelectedIndex()) {
					request(4, (String) room.getSelectedItem());
					System.out.print( room.getSelectedIndex());
				}
				temp = room.getSelectedIndex();
			}
		});

		c.add(panel);
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setSize(550, 600);

		addWindowListener(new WindowAdapter() {
			public void windowClosing(WindowEvent e) {
				if (isActive)
				{
					thread.close();
					thread.write("-1");
				}
				System.exit(0);
			}
		});
	}

	private class ItemHander implements ActionListener {
		public void actionPerformed(ActionEvent e) {

			if (e.getSource() == jmenuitem1[0]) {
				runClient();
			}
			else if (e.getSource() == jmenuitem1[1]) {
				jmenuitem1[0].setEnabled(true);
				jmenuitem1[1].setEnabled(false);
				jmenuitem1[2].setEnabled(false);
				jmenuitem3[0].setEnabled(false);
				jmenuitem3[1].setEnabled(false);
				jmenuitem3[2].setEnabled(false);
				jmenuitem3[3].setEnabled(false);
				jmenuitem3[4].setEnabled(false);
				jmenuitem3[5].setEnabled(false);
				thread.close();
				thread.write("-1");
			}
			else if ( jmenuitem1[2] == e.getSource() )
			{
				if (isActive)
				{
					thread.close();
					thread.write("-1");
				}
				System.exit(0);
			}

			if (e.getSource() == jmenuitem3[0]) {
				String newname = JOptionPane.showInputDialog(new Frame(),
						"請輸入新聊天室名稱：");
				if( newname != null && !newname.equals("") )
					request( 3, newname );
			} else if(e.getSource() == jmenuitem3[1]){
				sendfile();
			} else if(e.getSource() == jmenuitem3[2]){
				sendVideo();
			} else if(e.getSource() == jmenuitem3[3]){
				sendAudio();
			} else if(e.getSource() == jmenuitem3[4]){
				sendMovie();
			} else if(e.getSource() == jmenuitem3[5]){
				sendWave();
			}

			if (e.getSource() == jmenuitem4) {
				JOptionPane.showMessageDialog(null, "six's chatroom", "版本-0.1",
						JOptionPane.PLAIN_MESSAGE);
			}
		}
	}

	public void sendfile() {
		//read file
		String receiver = ( String ) listTalk.getSelectedItem();
		if( receiver.equals( "使用者列表：" ) || receiver.equals( username ) )
		{
			JOptionPane.showMessageDialog( null, "請先選擇傳送對象" );
			return;
		}
		JFileChooser fileChooser = new JFileChooser( "選擇傳送檔案" );
		fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
		int result = fileChooser.showOpenDialog(this);
		if (result != JFileChooser.APPROVE_OPTION)
			return;
		File sendFile = fileChooser.getSelectedFile();
		
		
		thread.write( "6" + receiver + "\n" + sendFile.getName() );
		SendFile fileTh = new SendFile( sendFile, host, this );
		fileTh.start();
	}

	private void addcomponent(Component component, int column, int row,
			int width, int height) {
		constraints.gridx = column;
		constraints.gridy = row;

		constraints.gridwidth = width;
		constraints.gridheight = height;
		layout.setConstraints(component, constraints);
		panel.add(component);
	}

	public void runClient() {
		Socket client;
		username = JOptionPane.showInputDialog(new Frame(), "請輸入登入帳號：");
		
		if( username == null )
			return;
		
		jmenuitem1[0].setEnabled(false);
		jmenuitem1[1].setEnabled(true);
		jmenuitem1[2].setEnabled(true);
		jmenuitem3[0].setEnabled(true);
		jmenuitem3[1].setEnabled(true);
		jmenuitem3[2].setEnabled(true);
		jmenuitem3[3].setEnabled(true);
		jmenuitem3[4].setEnabled(true);
		jmenuitem3[5].setEnabled(true);
		try {
			//			display.setText("Attempting connection\n");
			showText("Attempting connection\n", sas);
			client = new Socket( InetAddress.getByName( host ), 5000 );

			//			display.setText("Connected to: "
			//					+ client.getInetAddress().getHostName());
			showText("Connected to: " + client.getInetAddress().getHostName(),
					sas);

			thread = new ClientTh(client, this, username);
			thread.start();
			isActive = true;
	//		Secret sec = new Secret(thread);
	//		sec.run();

			//			display.setText("\nGot I/O streams\n");
//			showText("\nGot I/O streams\n", sas);
			//以上為connect時的hand-shaking，所以一定要照著抄，不然會和server連不起來
			//1.送username
			//2.接server的確定登入訊息

			enter.setEnabled(true);

		} catch (EOFException eof) {
			System.out.println("Server terminated connection");
		} catch (IOException io) {
			io.printStackTrace();
		}
		
	}

	private void sendData(String s) {
	//	System.out.print(colornumber);
		String Sfont = "$F$" + fontnumber;
		String Sfontsize = "$S$" + fontsizenumber;
		String Sfontcolor = "$C$" + colornumber;
		String Sfontstyle = "$Y$" + fontstylenumber;
		thread.write("0" + username + ">>> " + s + " " + Sfont + " "
				+ Sfontsize + " " + Sfontcolor + " " + Sfontstyle);
		//		display.setText("\n" + username + ">>> " + s);
	}

	public void request(int type, String s) {
		switch (type) {
		case 3:
			thread.write("3" + s);
			break;
		case 4:
			thread.write("4" + s);
			break;
		case 7:
			thread.write("72" + s);
			break;
		case 8:
			thread.write("82" + s);
			break;
		case 9:
			thread.write("92" + s);
			break;
		default:
			break;
		}
	}

	private void sendSecretTo(String sendTo, String s) {
		thread.write("2\n" + sendTo + "\n" + username + ">>> " + s);
	}

	public void listUsers(String msg) {
		listTalk.removeAllItems();
		listTalk.addItem("使用者列表：");
		StringTokenizer tokens = new StringTokenizer(msg);

		while (tokens.hasMoreTokens())
			listTalk.addItem(tokens.nextToken());
	}

	public void show_received_Text(String s) {
		if( s.indexOf(">") != -1
				&& s.substring( 0, s.indexOf(">")).equals( "SERVER" ) )
		{
			showText( s, null );
			setEndSelection();
			return;
		}
		set_received_font(s);//先把string傳入得到對方傳入的display參數
	
		StringTokenizer tokens = new StringTokenizer(s, " ");
		while (tokens.hasMoreTokens()) {
			String temp = tokens.nextToken();
			if( match_graph(temp) == false )
				//避免token出的string length<3 而出現exception
				if (temp.length() > 3 && !temp.substring(0, 3).equals("$F$")
						&& !temp.substring(0, 3).equals("$C$")
						&& !temp.substring(0, 3).equals("$Y$")
						&& !temp.substring(0, 3).equals("$S$"))
					showText(temp + " ", sas_received);
				else if (temp.length() <= 3)
					showText(temp + " ", sas_received);
		}
		showText("\n", sas_received);
//		toFront();
//		display.setSelectionEnd(display.getDocument().getLength());
		setEndSelection();
	}

	public void sendVideo()
	{
		String receiver = ( String ) listTalk.getSelectedItem();
		if( receiver.equals( "使用者列表：" ) || receiver.equals( username ) )
		{
			JOptionPane.showMessageDialog( null, "請先選擇傳送對象" );
			return;
		}
		mediaSender = new VideoSender();
		if( mediaSender.initialize() )
			request( 7, receiver + "\n" + thread.v_port );
	}
	
	public void sendAudio()
	{
		String receiver = ( String ) listTalk.getSelectedItem();
		if( receiver.equals( "使用者列表：" ) || receiver.equals( username ) )
		{
			JOptionPane.showMessageDialog( null, "請先選擇傳送對象" );
			return;
		}
		audioSender = new AudioSender();
		if( audioSender.initialize() )
			request( 8, receiver + "\n" + thread.a_port );
	}
	
	public void sendWave()
	{
		String receiver = ( String ) listTalk.getSelectedItem();
		if( receiver.equals( "使用者列表：" ) || receiver.equals( username ) )
		{
			JOptionPane.showMessageDialog( null, "請先選擇傳送對象" );
			return;
		}
		JFileChooser fileChooser = new JFileChooser( "選擇傳送檔案(WAV)" );
		fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
		int result = fileChooser.showOpenDialog( this );
		if( result != JFileChooser.APPROVE_OPTION )
			return;
		File wave = fileChooser.getSelectedFile();
		String filename = wave.getName();
		String type = filename.substring( filename.indexOf('.')+1 );
		showText( filename.substring( filename.indexOf('.')+1 ), null );
		if( !type.equals("wav") )
		{
			JOptionPane.showMessageDialog( null, "請選擇WAV格式" );
			return;
		}
		String path = wave.getPath();
		audioSender = new AudioSender( path );
		request( 8, receiver + "\n" + thread.a_port );
	}
	
	public void sendMovie()
	{
		String receiver = ( String ) listTalk.getSelectedItem();
		if( receiver.equals( "使用者列表：" ) || receiver.equals( username ) )
		{
			JOptionPane.showMessageDialog( null, "請先選擇傳送對象" );
			return;
		}
		JFileChooser fileChooser = new JFileChooser( "選擇傳送檔案(MPEG)" );
		fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
		int result = fileChooser.showOpenDialog( this );
		if( result != JFileChooser.APPROVE_OPTION )
			return;
		File movie = fileChooser.getSelectedFile();
		String filename = movie.getName();
		String type = filename.substring( filename.indexOf('.')+1 );
		showText( filename.substring( filename.indexOf('.')+1 ), null );
		if( !type.equals("mpg") && !type.equals("mpeg")	)
		{
			JOptionPane.showMessageDialog( null, "請選擇MPEG格式" );
			return;
		}
		String path = movie.getPath();
		movieSender = new MovieSender( path );
		request( 9, receiver + "\n" + thread.v_port );
	}
	
	//match $F$ $S$ $C$ $Y$
	public void set_received_font(String s) {
		StringTokenizer tokens = new StringTokenizer(s, " ");
		while (tokens.hasMoreTokens()) {
			String temp = tokens.nextToken();
			for (int i = 0; i < choosefont.enviroment.length; i++) {
				if (temp.equals("$F$" + i)) {
					StyleConstants.setFontFamily(sas_received,
							(String) choosefont.enviroment[i]);
				}
			}
			//default
			if (temp.equals("$F$49")) {
				StyleConstants.setFontFamily(sas_received, "Helvetica");
			}
			for (int i = 0; i < choosefont.sizeList.length; i++) {
				if (temp.equals("$S$" + i)) {
					StyleConstants.setFontSize(sas_received, Integer
							.parseInt(choosefont.sizeList[i]));
				}
			}
			if (temp.equals("$Y$0\n")) {
				StyleConstants.setBold(sas_received, false);
				StyleConstants.setItalic(sas_received, false);
			} else if (temp.equals("$Y$1")) {
				StyleConstants.setBold(sas_received, true);
				StyleConstants.setItalic(sas_received, false);
			} else if (temp.equals("$Y$2")) {
				StyleConstants.setBold(sas_received, false);
				StyleConstants.setItalic(sas_received, true);
			} else if (temp.equals("$Y$3")) {
				StyleConstants.setBold(sas_received, true);
				StyleConstants.setItalic(sas_received, true);
			}
			for (int i = 0; i < choosefont.colorname.length; i++) {
				if (temp.equals("$C$" + i)) {
					StyleConstants.setForeground(sas_received,
							choosefont.colorsetting[i]);
				}
			}
		}
	}

	/////////////////////////////////////////////////
	//設定display字型
	public void setAttribute(JLabel sample) {
		StyleConstants.setFontFamily(sas, sample.getFont().getFamily());
		StyleConstants.setFontSize(sas, sample.getFont().getSize());
		StyleConstants.setForeground(sas, sample.getForeground());

		if (sample.getFont().getStyle() == 0) {
			StyleConstants.setBold(sas, false);
			StyleConstants.setItalic(sas, false);
		} else if (sample.getFont().getStyle() == 1) {
			StyleConstants.setBold(sas, true);
			StyleConstants.setItalic(sas, false);
		} else if (sample.getFont().getStyle() == 2) {
			StyleConstants.setBold(sas, false);
			StyleConstants.setItalic(sas, true);
		} else if (sample.getFont().getStyle() == 3) {
			StyleConstants.setBold(sas, true);
			StyleConstants.setItalic(sas, true);
		}
	}

	//	public void setAttribute(Font font){
	//		StyleConstants.setFontFamily(sas, font.getFamily());
	//		StyleConstants.setFontSize(sas, font.getSize());
	//		StyleConstants.setForeground(sas, fontchooser.getfontColor() );
	//		
	//		if(font.getStyle()==0){
	//			StyleConstants.setBold(sas, false);
	//			StyleConstants.setItalic(sas, false);
	//		}
	//		else if(font.getStyle()==1){
	//			StyleConstants.setBold(sas, true);
	//			StyleConstants.setItalic(sas, false);
	//			}
	//		else if(font.getStyle()==2){
	//			StyleConstants.setBold(sas, false);
	//			StyleConstants.setItalic(sas, true);
	//		}
	//		else if(font.getStyle()==3){
	//			StyleConstants.setBold(sas, true);
	//			StyleConstants.setItalic(sas,true);
	//		}
	//	}
	public void showText(String text, AttributeSet set) {
		try {
			display.getDocument().insertString(
					display.getDocument().getLength(), text, set);
		} catch (BadLocationException e) {
			e.printStackTrace();
		}
	}

	//	 Needed for inserting icons in the right places
	public void setEndSelection() {
		display.setSelectionStart(display.getDocument().getLength());
		display.setSelectionEnd(display.getDocument().getLength());
	}

	//===============================================================//
	public static void main(String args[]) {

		Client app = new Client( args[0] );
		JFrame.setDefaultLookAndFeelDecorated(true);
		app.setVisible(true);
		app.setLocation(100, 100);
		//		app.runClient();
	}

	///////////////////////////////////////////////////////////////////////////////
	private class buttonaction implements ActionListener {
		public void actionPerformed(ActionEvent e) {
			String t = "";
			for (int i = 0; i < 36; i++) {
				if (e.getSource() == g.Sbutton[i]) {
					t = " S" + i + " ";
					g.showgraph.setIcon(g.Sbutton[i].getIcon());
					g.showtext.setText(t);
				}
			}
			for (int i = 0; i < 16; i++) {
				if (e.getSource() == g.Dbutton[i]) {
					t = " D" + i + " ";
					
					g.showgraph.setIcon(g.Dbutton[i].getIcon());
					g.showtext.setText(t);
					

				}
			}
			for (int i = 0; i < 18; i++) {
				if (e.getSource() == g.Cbutton[i]) {
					t = " C" + i + " ";
					
					g.showtext.setText(t);
					g.showgraph.setIcon(g.Cbutton[i].getIcon());
				}
			}
			if (e.getSource() == g.sure) {
				g.setVisible(false);
				enter.setText(enter.getText() + g.showtext.getText());
			}
			if (e.getSource() == g.cancel) {
				enter.setText(enter.getText());
				g.setVisible(false);
			}
		}
	}
    //對應graph
	public boolean match_graph(String s) {
		for (int i = 0; i < 36; i++) {
			if (s.equals("S" + i)) {
				setEndSelection();
				display.insertIcon(g.Sbutton[i].getIcon());
				return true;
			}
		}
		for (int i = 0; i < 16; i++) {
			if (s.equals("D" + i)) {
				setEndSelection();
				display.insertIcon(g.Dbutton[i].getIcon());
				return true;
			}
		}
		for (int i = 0; i < 18; i++) {
			if (s.equals("C" + i)) {
				setEndSelection();
				display.insertIcon(g.Cbutton[i].getIcon());
				return true;
			}
		}
		return false;
	}

	//============================================================

	///////////////////fontchooser////////////////////////////////////////

	void showSample() {
		int g = 0;
		try {
			g = Integer.parseInt(choosefont.SizeList.getSelectedValue());
		} catch (NumberFormatException nfe) {
		}
		String st = choosefont.StyleList.getSelectedValue();
		int s = 0;//Font.PLAIN;
		if (st.equalsIgnoreCase("Bold"))
			s = 1;//Font.BOLD;
		if (st.equalsIgnoreCase("Italic"))
			s = 2;//Font.ITALIC;
		if (st.equalsIgnoreCase("Bold+Italic")) {
			s = 3;//Font.ITALIC+Font.BOLD;;
		}
		//fo=FontList.getSelectedValue();
		choosefont.Sample.setFont(new Font(choosefont.FontList
				.getSelectedValue(), s, g));

		
		choosefont.Sample.setText(" choose Font and Size ");
	}
	///////////////////////////////////////////////////////////////////////
}