package com.example.smarthome;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.ToggleButton;


public class SecondPage extends Activity {
	static final String SERVER_IP = "10.242.14.54";
	static final int SERVER_PORT = 8889;

	Handler handler = new Handler();									//initialising components
	Handler hand= new Handler(Looper.getMainLooper());
	static Socket socket;
	ToggleButton tb1,tb2;
	PrintWriter printWriter;
	int sign,box;
	Button b1a,b1b,b1c,b2a,b2b,b2c,btn;
	Switch switch1,switch2;
	//String m1,m2,w1,w2,w3,w4,w5;
	TextView p1,v1,c1,e1,p2,v2,c2,e2,msg1,msg2,msg;
	Intent yesint;
	EditText e;
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_second_page);

		p1 = (TextView) findViewById(R.id.p1);							//Binding components
		v1 = (TextView) findViewById(R.id.v1);
		c1 = (TextView) findViewById(R.id.c1);
		e1 = (TextView) findViewById(R.id.e1);
		p2 = (TextView) findViewById(R.id.p11);
		v2 = (TextView) findViewById(R.id.v11);
		c2 = (TextView) findViewById(R.id.c11);
		e2 = (TextView) findViewById(R.id.e11);
		msg1 = (TextView) findViewById(R.id.msg1);
		msg2 = (TextView) findViewById(R.id.msg2);
		msg = (TextView) findViewById(R.id.msg);
		tb1= (ToggleButton) findViewById(R.id.toggleButton1);
		tb2= (ToggleButton) findViewById(R.id.toggleButton11);
		b1a= (Button)findViewById(R.id.b1a);
		b1b= (Button)findViewById(R.id.b1b);
		b1c= (Button)findViewById(R.id.b1c);
		b2a= (Button)findViewById(R.id.b2a);
		b2b= (Button)findViewById(R.id.b2b);
		b2c= (Button)findViewById(R.id.b2c);
		btn= (Button) findViewById(R.id.button1);
		switch1= (Switch)findViewById(R.id.switch1);
		switch2= (Switch)findViewById(R.id.switch11);
		b1b=(Button)findViewById(R.id.b1b);
		e= (EditText)findViewById(R.id.editText1);
		
		btn.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				Thread clientThread7 = new Thread(new ClientThread());
				clientThread7.start();
				try{printWriter.println("l"+e.getText().toString());}catch(Exception e){}
			}
		});
		
		switch1.setOnCheckedChangeListener(new OnCheckedChangeListener() {
			
			@Override
			public void onCheckedChanged(CompoundButton arg0, boolean arg1) {			//Switch 1
				if(switch1.isChecked()){
					box=1;
	            	Thread clientThreada = new Thread(new ClientThread());
					clientThreada.start();
	            	try{printWriter.println("start");}catch(Exception e){};
				}
				else{
					msg1.setText("meter turned off");
				}
				
			}
		});
		
		switch2.setOnCheckedChangeListener(new OnCheckedChangeListener() {				//Switch 2
			
			@Override
			public void onCheckedChanged(CompoundButton arg0, boolean arg1) {
				if(switch2.isChecked()){
					box=2;
	            	Thread clientThreada = new Thread(new ClientThread());
					clientThreada.start();
	            	try{printWriter.println("start1");}catch(Exception e){};
				}
				else{
					msg2.setText("meter turned off");
				}
				
			}
		});
		
	}

	@Override
	protected void onStart() {							//On start
		super.onStart();
		
	}

	@Override
	protected void onStop() {							//On Stop
		super.onStop();
		
	}
	
	public void onClick(final View view) {								//action taken when Clicking on Various Buttons
		
		handler.post(new Runnable() {
			@Override
			public void run() {
				if(view.getId()==R.id.toggleButton1&&tb1.isChecked()){			//toggle Buttons to create connection Enabling Buttons
					box=1;
					setValues(R.id.b1a,true);
					setValues(R.id.b1b,true);
					setValues(R.id.b1c,true);
					setValues(R.id.switch1,true);
					Thread clientThreada= new Thread(new ClientThread());
					clientThreada.start();
	            	try{printWriter.println("hello ");}catch(Exception e){}
				}
				
				if(view.getId()==R.id.toggleButton11&&tb2.isChecked()){
					box=2;
					setValues(R.id.b2a,true);
					setValues(R.id.b2b,true);
					setValues(R.id.b2c,true);
					setValues(R.id.switch11,true);
					Thread clientThreada= new Thread(new ClientThread());
					clientThreada.start();
	            	try{printWriter.println("hello ");}catch(Exception e){}
				}
				
				if(view.getId()==R.id.toggleButton1&&(!tb1.isChecked())){		//Disabling Buttons While Toggle off
					box=1;
					setValues(R.id.b1a,false);
					setValues(R.id.b1b,false);
					setValues(R.id.b1c,false);
					setValues(R.id.switch1,false);
					msg1.setText("disconnected");
				}
				else if(view.getId()==R.id.toggleButton11&&(!tb2.isChecked())){
					box=2;
					setValues(R.id.b2a,false);
					setValues(R.id.b2b,false);
					setValues(R.id.b2c,false);
					setValues(R.id.switch11,false);
					msg2.setText("disconnected");
				}
				
				switch(view.getId())					//Switch to select Appropriate Button
		        {
		            	
		            case R.id.b1a:
		            	box=1;
		            	Thread clientThread = new Thread(new ClientThread());
						clientThread.start();
		            	try{printWriter.println("1a");}catch(Exception e){}
		            	
		                break;
		            case R.id.b1b:
		            	box=1;
		            	Thread clientThread1 = new Thread(new ClientThread());
						clientThread1.start();
						try{printWriter.println("1b");}catch(Exception e){}
						
		            	
		                break;
		            case R.id.b1c:
		            	box=1;
		            	Thread clientThread2= new Thread(new ClientThread());
						clientThread2.start();
						try{printWriter.println("1c");}catch(Exception e){}
		                break;
		            case R.id.b2a:
		            	box=2;
		            	Thread clientThread3 = new Thread(new ClientThread());
						clientThread3.start();
						try{printWriter.println("2a");}catch(Exception e){}
		                break;
		            case R.id.b2b:
		            	box=2;
		            	Thread clientThread4 = new Thread(new ClientThread());
						clientThread4.start();
						try{printWriter.println("2b");}catch(Exception e){}
		                break;
		            case R.id.b2c:
		            	box=2;
		            	Thread clientThread5 = new Thread(new ClientThread());
						clientThread5.start();
						try{printWriter.println("2c");}catch(Exception e){}
		                break;
		            case R.id.button5:
		            	Thread clientThread6 = new Thread(new ClientThread());
						clientThread6.start();
						try{printWriter.println("m");}catch(Exception e){}
		          /*  case R.id.button1:
		            	Thread clientThread7 = new Thread(new ClientThread());
						clientThread7.start();
						try{printWriter.println("l"+e.getText().toString());}catch(Exception e){}*/
		        }
				
				
			}
		});
		
		
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {						//Default Options Menu
		getMenuInflater().inflate(R.menu.second_page, menu);
		return true;
	}

	public class ClientThread implements Runnable {
		public void run() {
			try {
				InetAddress serverAddr = InetAddress.getByName(SERVER_IP);	//Create Socket

				handler.post(new Runnable() {
					@Override
					public void run() {
						if(box==1)
							msg1.setText( "Connected to the server");
						if(box==2)
							msg2.setText( "Connected to the server");
					}
				});

			socket = new Socket(serverAddr, SERVER_PORT);				
			try {
				printWriter = new PrintWriter(new BufferedWriter(			//PrintWriter For Output
					new OutputStreamWriter(socket.getOutputStream())),true);

					//---get an InputStream object to read from the server---
					BufferedReader br = new BufferedReader(						//BufferedReader For Input
						new InputStreamReader(socket.getInputStream()));

					try {
						//---read all incoming data terminated with a \n
						// char---
						String line = null;
						while ((line = br.readLine()) != null) {
							final String strReceived = line,chk1="a",chk2="b",chk3="c",chk4="m";
						if(chk1.equals(strReceived.substring(0, 1))){			//Actions According To Button
							final String s1,s2,s3,s4;
							s1=strReceived.substring(1,5);
							s2=strReceived.substring(5,9);
							s3=strReceived.substring(9,13);
							s4=strReceived.substring(13,17);
							

							handler.post(new Runnable() {				//Current data 
								@Override
								public void run() {
									if(box==1){
										p1.setText(s1+" "+"Watt");
										v1.setText(s2+" "+"Volt");
										c1.setText(s3+" "+"Ampere");
										e1.setText(s4+" "+"KWatt hr.");
									}
									else if(box==2){
										p2.setText(s1+" "+"Watt");
										v2.setText(s2+" "+"Volt");
										c2.setText(s3+" "+"Ampere");
										e2.setText(s4+" "+"KWatt hr.");
									}
								}
							});
							}
						else if(chk2.equals(strReceived.substring(0, 1))){		//Previous Day Data
								final String m1,m2;
								m1= strReceived.substring(1,4);
								m2= strReceived.substring(4,7);
								Log.i("thread","one socket closed: Finished"+" "+m1+" "+m2);
								handler.post(new Runnable() {
									@Override
									public void run() {
										Intent intent=new Intent(SecondPage.this,YesterDay.class);
										intent.putExtra("str1", m1);
										intent.putExtra("str2", m2);
										startActivity(intent);
										
									}
								});
							}
							
						else if(chk3.equals(strReceived.substring(0, 1))){		//Previous Weeks Data
							/*final String w1,w2,w3,w4,w5;
							w1= strReceived.substring(1,4);
							w2= strReceived.substring(4,7);
							w3= strReceived.substring(7,10);
							w4= strReceived.substring(10,13);
							w5= strReceived.substring(13,16);*/
							//Log.i("thread","two socket closed: Finished"+" "+w1+" "+w2+" "+w3+" "+w4+" "+w5);
							handler.post(new Runnable() {
									
									@Override
									public void run() {
										
										
										Intent intent=new Intent(SecondPage.this,Week.class);
										intent.putExtra("str11", strReceived);
										/*intent.putExtra("str21", w2);
										intent.putExtra("str31", w3);
										intent.putExtra("str41", w4);
										intent.putExtra("str51", w5);*/
										startActivity(intent);
										
									}
								});
							}
						else if(chk4.equals(strReceived.substring(0, 1))){		//Previous Month Command
							final String m1,m2;
							m1= strReceived.substring(1,4);
							m2= strReceived.substring(4,7);
							handler.post(new Runnable() {
								@Override
								public void run() {
									Intent intent=new Intent(SecondPage.this,Month.class);
									intent.putExtra("str1", m1);
									intent.putExtra("str2", m2);
									startActivity(intent);
									
								}
							});
						}
						}

						//---disconnected from the server---
						handler.post(new Runnable() {			
							@Override
							public void run() {
								if(box==1)
									msg1.setText("Client disconnected");
								else
									msg2.setText("Client disconnected");
							}
						});

					} catch (Exception e) {
						final String error = e.getLocalizedMessage();
						handler.post(new Runnable() {
							@Override
							public void run() {
								msg.setText( error);
							}
						});
					}

				} catch (Exception e) {
					final String error = e.getLocalizedMessage();
					handler.post(new Runnable() {
						@Override
						public void run() {
							msg.setText(error);
						}
					});
				}

				handler.post(new Runnable() {
					@Override
					public void run() {
						msg.setText( "Connection closed.");
					}
				});

			} catch (Exception e) {
				final String error = e.getLocalizedMessage();
				handler.post(new Runnable() {
					@Override
					public void run() {
						msg.setText( error);
					}
				});
			}finally {
				try {								//Socket close After End Of Each Thread
					socket.shutdownInput();
					socket.close();
				} catch (IOException e) {
					e.printStackTrace();
				} catch (Exception e) {
					e.printStackTrace();
				}
				
			}
		}
	}
	
	 private void setValues(int view, boolean value)				//To enable Or Disable Button
	    {
	        switch(view)
	        {
	            case R.id.b1a: b1a.setEnabled(value); break;
	            case R.id.b1b: b1b.setEnabled(value); break;
	            case R.id.b1c: b1c.setEnabled(value); break;
	            case R.id.b2a: b2a.setEnabled(value); break;
	            case R.id.b2b: b2b.setEnabled(value); break;
	            case R.id.b2c: b2c.setEnabled(value); break;
	            case R.id.switch1: switch1.setEnabled(value); break;
	            case R.id.switch11: switch2.setEnabled(value); break;
	            
	        }
	    }
    
}

