package com.hmedia.controller;

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TextView;
import android.widget.Toast;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.InputStreamReader;

import java.net.Socket;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Timer;
import java.util.TimerTask;


public class MainActivity extends Activity implements OnClickListener, OnSeekBarChangeListener, OnItemClickListener, OnCheckedChangeListener {

	Socket socket = null;
	DataOutputStream dataOutputStream = null;
	DataInputStream dataInputStream = null;
	EditText serverAddress, portNum, sendMsg;
	Button connectBtn, disconnectBtn, sendBtn, playBtn, pauseBtn, stopBtn, chooseFileBtn, nextBtn;
	TextView view1;
	CheckBox displayTimeCbx;
	SeekBar seek;
	ListView playListView;
	Timer t;
	BufferedReader inR;
	String temp;
	ArrayList<String> playList=new ArrayList<String>();
	ArrayAdapter<String> adapter;
	boolean read, cancelled, seekChange;
	MainActivity parentID;
	
	class readText extends TimerTask{
		@Override
		public void run() {
			// TODO Auto-generated method stub
			try {
				read = true;
				if (dataInputStream.available() > 0)
				{
					inR = new BufferedReader(new InputStreamReader(socket.getInputStream()));
					while ((temp = inR.readLine()) != null)
					{
						read = false;
						MainActivity.this.runOnUiThread(new Runnable(){
							@Override
							public void run(){
								if (temp.charAt(0) == 'f') {
									playList.add(temp.substring(2));
									adapter = new ArrayAdapter <String> (parentID, android.R.layout.simple_list_item_1, playList);
									playListView.setAdapter(adapter);
									read = true;
								}
								else {
									view1.setText(temp);
									int pos, len;
									pos = Integer.parseInt(temp.substring((temp.indexOf(':') + 2), (temp.indexOf('/') - 1)));
									len = Integer.parseInt(temp.substring((temp.indexOf('/') + 2), (temp.length())));
									try {
										if (seek.getMax() != len)
											seek.setMax(len);
										if (seekChange == false)
											seek.setProgress(pos);
									}
									catch (Exception e) {
										sendMsg.setText(e.toString());
									}
									read = true;
								}
							}
						});
						while (read == false);
					}
				}
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			if (cancelled == false)
				t.schedule(new readText(), 0, 1);
		}
	}
		
	
	@Override
	public void onCreate(Bundle savedInstanceState) { 
		
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		parentID = this;
		
		serverAddress = (EditText) findViewById(R.id.editText1);
		portNum = (EditText) findViewById(R.id.editText2);
		sendMsg = (EditText) findViewById(R.id.editText3);
		view1 = (TextView) findViewById(R.id.textView1);
		seek = (SeekBar) findViewById(R.id.seekBar1);
		playListView = (ListView) findViewById(R.id.listView1);
		displayTimeCbx = (CheckBox) findViewById(R.id.checkBox1);
		connectBtn = (Button) findViewById(R.id.button1);
		disconnectBtn = (Button) findViewById(R.id.button2);
		sendBtn = (Button) findViewById(R.id.button3);
		playBtn = (Button) findViewById(R.id.button4);
		pauseBtn = (Button) findViewById(R.id.button5);
		stopBtn = (Button) findViewById(R.id.button6);
		chooseFileBtn = (Button) findViewById(R.id.button7);
		nextBtn = (Button) findViewById(R.id.button8);
		
		seek.setOnSeekBarChangeListener(this);
		connectBtn.setOnClickListener(this);
		disconnectBtn.setOnClickListener(this);
		sendBtn.setOnClickListener(this);
		playBtn.setOnClickListener(this);
		pauseBtn.setOnClickListener(this);
		stopBtn.setOnClickListener(this);
		chooseFileBtn.setOnClickListener(this);
		nextBtn.setOnClickListener(this);
		playListView.setOnItemClickListener(this);
		displayTimeCbx.setOnCheckedChangeListener(this);
		
		disconnectBtn.setEnabled(false);
		cancelled = false;
		seekChange = false;
		
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.activity_main, menu);
		return true;
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub

		switch (v.getId())
		{
		// Connect button
		case R.id.button1:
			playListView.setAdapter(null);
			new Thread(new Runnable() {
			    public void run() {
			    	t = new Timer();
			    	try
					{
						socket = new Socket(serverAddress.getText().toString().trim(), 
								Integer.parseInt(portNum.getText().toString().trim()));
						dataOutputStream = new DataOutputStream(socket.getOutputStream());
						dataInputStream = new DataInputStream(socket.getInputStream());

						dataOutputStream.writeBytes("Hello Server\n");
						dataOutputStream.flush();
						t.schedule(new readText(), 0, 300);
						//t.scheduleAtFixedRate(new readText(), 0, 300);
					}
					catch (UnknownHostException e) 
					{  
						//if specified ip address is not found in the network  
						e.printStackTrace();  
					} 
					catch (IOException e) 
					{  
						// TODO Auto-generated catch block  
						e.printStackTrace();  
					}
			    }
			}).start();
			connectBtn.setEnabled(false);
			disconnectBtn.setEnabled(true);
			break;
		// Disconnect button
		case R.id.button2:
			if (socket != null)
			{  
				try 
				{  
					//close socket connection after using it otherwise next time when u reconnect on  the same port  
					// it will throw error if you don't close it   
					dataOutputStream.writeBytes("QUIT ###\n");
					dataOutputStream.flush();
					t.cancel();			
					cancelled = true;
					socket.close();  
				} 
				catch (IOException e) 
				{  
					// TODO Auto-generated catch block  
					e.printStackTrace(); 
					Toast.makeText(this, "Error 3", Toast.LENGTH_LONG).show();
				}  
			}  
			
			connectBtn.setEnabled(true);
			disconnectBtn.setEnabled(false);
			
			if (dataOutputStream != null)
			{  
				try 
				{  
					//close output stream  
					dataOutputStream.close();  
				} 
				catch (IOException e) 
				{  
					// TODO Auto-generated catch block  
					e.printStackTrace();  
					Toast.makeText(this, "Error 4", Toast.LENGTH_LONG).show();
				}  
			}  

			if (dataInputStream != null)
			{  
				try 
				{  
					//close input stream  
					dataInputStream.close();  
				} 
				catch (IOException e) 
				{  
					// TODO Auto-generated catch block  
					e.printStackTrace();  
					Toast.makeText(this, "Error 5", Toast.LENGTH_LONG).show();
				}  
			}  
			break;
			// Send button
		case R.id.button3:
			try {
				dataOutputStream.writeBytes(sendMsg.getText().toString());
				dataOutputStream.flush();
				Toast.makeText(this, sendMsg.getText().toString(), Toast.LENGTH_SHORT).show();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			break;
			// Play button
		case R.id.button4:
			try {
				dataOutputStream.writeBytes("PLAY ###");
				dataOutputStream.flush();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			break;
			// Pause button
		case R.id.button5:
			try {
				dataOutputStream.writeBytes("PAUSE ###");
				dataOutputStream.flush();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			break;
			// Stop button
		case R.id.button6:
			try {
				dataOutputStream.writeBytes("STOP ###");
				dataOutputStream.flush();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			break;
		case R.id.button7:
/*			Intent intent = new Intent(getBaseContext(), FileDialog.class);
            intent.putExtra(FileDialog.START_PATH, "/sdcard");
            
            //can user select directories or not
            intent.putExtra(FileDialog.CAN_SELECT_DIR, true);
            
            //alternatively you can set file filter
            //intent.putExtra(FileDialog.FORMAT_FILTER, new String[] { "png" });
            
            startActivityForResult(intent, REQUEST_SAVE);
	*/		break;
		case R.id.button8:
			try {
				dataOutputStream.writeBytes("NEXT ###");
				dataOutputStream.flush();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			break;
		}
		
	}

	@Override
	public void onProgressChanged(SeekBar seekBar, int progress,
			boolean fromUser) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onStartTrackingTouch(SeekBar seekBar) {
		// TODO Auto-generated method stub
		seekChange = true;
	}

	@Override
	public void onStopTrackingTouch(SeekBar seekBar) {
		// TODO Auto-generated method stub
		try {
			dataOutputStream.writeBytes("POSITION ### p" + seekBar.getProgress() + "\n");
			dataOutputStream.flush();
			seekChange = false;
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	@Override
	public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
		// TODO Auto-generated method stub
		try {
			dataOutputStream.writeBytes("CHANGE ### " + arg2 + "\n");
			dataOutputStream.flush();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	@Override
	public void onBackPressed() {
		// TODO Auto-generated method stub
		if (socket != null)
		{  
			try 
			{  
				//close socket connection after using it otherwise next time when u reconnect on  the same port  
				// it will throw error if you don't close it   
				dataOutputStream.writeBytes("QUIT ###\n");
				dataOutputStream.flush();
				t.cancel();			
				cancelled = true;
				socket.close();  
			} 
			catch (IOException e) 
			{  
				// TODO Auto-generated catch block  
				e.printStackTrace(); 
				Toast.makeText(this, "Error 3", Toast.LENGTH_LONG).show();
			}  
		}  
		
		if (dataOutputStream != null)
		{  
			try 
			{  
				//close output stream  
				dataOutputStream.close();  
			} 
			catch (IOException e) 
			{  
				// TODO Auto-generated catch block  
				e.printStackTrace();  
				Toast.makeText(this, "Error 4", Toast.LENGTH_LONG).show();
			}  
		}  

		if (dataInputStream != null)
		{  
			try 
			{  
				//close input stream  
				dataInputStream.close();  
			} 
			catch (IOException e) 
			{  
				// TODO Auto-generated catch block  
				e.printStackTrace();  
				Toast.makeText(this, "Error 5", Toast.LENGTH_LONG).show();
			}  
		}  

		super.onBackPressed();
	}

	@Override
	public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
		// TODO Auto-generated method stub
		if (isChecked == true) {
			try {
				dataOutputStream.writeBytes("TIME ### " + "1" + "\n");
				dataOutputStream.flush();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		else {
			try {
				dataOutputStream.writeBytes("TIME ### " + "0" + "\n");
				dataOutputStream.flush();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
	}	
}
