package com.wireless.apa;

import java.io.IOException;
import java.io.PrintWriter;
import java.net.ConnectException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketAddress;
import java.net.UnknownHostException;

import android.app.Activity;
import android.os.CountDownTimer;
import android.os.Looper;
import android.util.Log;

public class TCPHelper extends Activity {

	public static void emitMessage(Activity a, String msg)
			throws UnknownHostException {
		int port = Integer.parseInt(PropertiesHelper.getInstance().getProperty(
				"PORT"));
		String server_IP = PropertiesHelper.getInstance().getProperty("IP");

		Thread t = new Thread(new Client(a, port, msg, server_IP));
		t.start();

	}
} // end UDPHelper

class Client implements Runnable {

	int port;
	Activity a;
	// DatagramSocket s;
	Socket client;
	String server_IP;
	PrintWriter printwriter;
	String msg;
	Boolean runable;

	public Client(Activity _a, int _port, String _msg, String _server_IP) {

		server_IP = _server_IP;
		a = _a;
		port = _port;

		msg = _msg;
		runable = false;
		

	}

	public void run() {
		
		Looper.prepare();
		  try {	
			  	client = new Socket();
			  	InetSocketAddress Address = new InetSocketAddress(server_IP,port);
				client.connect(Address, 5000); 
			  	//client = new Socket(server_IP,port);				
				
				runable = true;
			} catch (IllegalArgumentException  ie) {
				runable = false;
				ie.printStackTrace();
			} catch (IOException  oe) {
				runable = false;
				ActivityHelper.showMessage(a, "CHECK IF THE SERVER IS ONLINE OR CHECK IP: ("+ server_IP +") AND PORT: ("+ port +")");
				oe.printStackTrace();
			} catch (Exception  e) {
				runable = false;
				ActivityHelper.showMessage(a, "ERROR");
				e.printStackTrace();
			} 
		  
				
		if (runable == true) {
			try {
				PrintWriter printwriter;
				printwriter = new PrintWriter(client.getOutputStream(), true);
				printwriter.write(msg); // write the message to output stream
				// printwriter.flush();
				printwriter.close();
				client.close(); // closing the connection

			} catch (UnknownHostException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		

		Looper.loop();

	} // end run()

} // end Client

