package com.app.downloadstream1;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import net.HttpActionManager;
import System.Sys;
import android.app.Activity;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MenuItem.OnMenuItemClickListener;
import android.widget.Toast;

public class DownloadStream extends Activity {
	public static final String TAG = "DownloadStream";
	private String video_3gp_h263 = "http://www.iratao.com/wordpress/wp-content/uploads/2009/10/recording_h263.3gp";
	//private String video_3gp_h264 = "";
	private String video_3gp_mpeg_sp = "http://www.iratao.com/wordpress/wp-content/uploads/2009/10/recording_mpeg_sp.3gp";
	//private static final String STREAM_URI = "http://www.iratao.com/wordpress/wp-content/uploads/2009/10/squirrel-playing-football.3gp";
	private static final String STREAM_URI = "http://www.iratao.com/wordpress/wp-content/uploads/2009/10/recording_h263.3gp";
	//private static final String CACHE_PATH = "/sdcard/football.3gp";
	private static final String LOCAL_PATH = "/sdcard/howdoyousleep.3gp";
	private static final String CACHE_PATH = "/sdcard/test_1.3gp";
	
	private final DownloadManager mManager = new DownloadManager(this);
	
	private HttpActionManager httpManager = new HttpActionManager();
	
	private Preview mPreview;
	private int mVideoWidth;
	private int mVideoHeight;
	
	private int eid;
	
	boolean playing = false;
	
	private final StreamMediaPlayer mPlayer = new StreamMediaPlayer();
	private List<String> paths;
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mPreview = new Preview(this);
        setContentView(mPreview);
        paths = new ArrayList<String>();
        //setContentView(R.layout.main);
    }
    
    @Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuItem playLocal = menu.add("Play(Local)");
		MenuItem playNet = menu.add("Play(Net)");
		MenuItem start_download = menu.add("Download");
		playLocal.setOnMenuItemClickListener(play_local);
		playNet.setOnMenuItemClickListener(play_net);
		start_download.setOnMenuItemClickListener(download);
		return super.onCreateOptionsMenu(menu);
	}
    
    @Override
	protected void onDestroy()
	{
	    mPlayer.stop();
		mPlayer.reset();
		mPlayer.release();
		mManager.stopDownload();
		super.onDestroy();
	}
    
    public boolean startplay(String path) {
    	StreamMediaPlayer player = mPlayer;
		
		player.reset();
		
		player.setDisplay(mPreview.getHolder());
		
		
		DownloadManager.Download dl =
			  mManager.getCurrentDownload();
		//String path = paths.get(0);
		String video_url = "http://"+ Sys.HOST + ":" + Sys.port 
		+ "/eventbook/doServlet/ShowVideo?name="+path;
		if (dl == null)
		{
			try {
				dl = mManager.startDownload(video_url, CACHE_PATH);
			} catch (IOException e) {
				Log.e(TAG, "Crap", e);
			}
		}
		try {
			player.setDataSource(new TailStream(dl));
		}catch (Exception e) {
			Toast.makeText(DownloadStream.this,
					  "Fatal MediaPlayer error: " + e.toString(), Toast.LENGTH_LONG)
					    .show();
			mManager.stopDownload();
			player.reset();
			return false;
		}
		setPlaying(true);
		player.prepareAsync();
		
		player.setOnBufferingUpdateListener(mBufferListener);
		player.setOnPreparedListener(mPreparedListener);
		player.setOnErrorListener(mErrorListener);
		player.setOnCompletionListener(mCompletionListener);
		player.setAudioStreamType(AudioManager.STREAM_MUSIC);
		
		Log.i(TAG, "Should be buffering...");
		return true;
    }
    
    public void setPlaying(boolean b) {
    	playing = b;
    }
    
    private final OnMenuItemClickListener play_local = new OnMenuItemClickListener() {
		
		public boolean onMenuItemClick(MenuItem item) {
            StreamMediaPlayer player = mPlayer;
    		
    		player.reset();
    		try {
				player.setDataSource(LOCAL_PATH);
			} catch (IllegalArgumentException e) {
				e.printStackTrace();
			} catch (IllegalStateException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
			player.setDisplay(mPreview.getHolder());
		    player.prepareAsync();
			
			
			player.setOnBufferingUpdateListener(mBufferListener);
			player.setOnPreparedListener(mPreparedListener);
			player.setOnErrorListener(mErrorListener);
			player.setOnCompletionListener(mCompletionListener);
			player.setAudioStreamType(AudioManager.STREAM_MUSIC);
			return true;

		}
    };
    
    private final OnMenuItemClickListener play_net = new OnMenuItemClickListener() {

		public boolean onMenuItemClick(MenuItem item) {
			
			eid = 2;
			
			
			try {
				paths = httpManager.getVideo(eid);
				
			} catch (Exception e1) {
				Log.e(TAG, e1.toString());
			}
			
			
			
			/**
			String video_url = "http://"+ Sys.HOST + ":" + Sys.port 
			+ "/eventbook/doServlet/ShowVideo?name="+paths.get(0);
			
			if (dl == null)
			{
				try {
					dl = mManager.startDownload(video_url, CACHE_PATH);
				} catch (IOException e) {
					Log.e(TAG, "Crap", e);
				}
			}
			try {
				player.setDataSource(new TailStream(dl));
			}catch (Exception e) {
				Toast.makeText(DownloadStream.this,
						  "Fatal MediaPlayer error: " + e.toString(), Toast.LENGTH_LONG)
						    .show();
				mManager.stopDownload();
				player.reset();
				return false;
			}
			//setPlaying(true);
			player.prepareAsync();
			
			player.setOnBufferingUpdateListener(mBufferListener);
			player.setOnPreparedListener(mPreparedListener);
			player.setOnErrorListener(mErrorListener);
			player.setOnCompletionListener(mCompletionListener);
			player.setAudioStreamType(AudioManager.STREAM_MUSIC);
			
			Log.i(TAG, "Should be buffering...");
			*/
			
			new Thread() {
				public void run() {
					int i = 0;
					while(i < paths.size()) {
						while(playing){}
						startplay(paths.get(i));
						i++;
					}	
				}
			}.start();
	
			return true;
		
		}
			
    };
    
    
    private final OnMenuItemClickListener download = new OnMenuItemClickListener() {

		public boolean onMenuItemClick(MenuItem item) {
			try{

    			DownloadManager.Download d;

    			if ((mManager.isDownloading(STREAM_URI)) == false)
    			{
    				try {
    					mManager.startDownload(STREAM_URI, CACHE_PATH);
    				} catch (IOException e) {
    					Log.e(TAG, "Crap", e);
    				}
    			}
    			else
    			{
    				Toast.makeText(DownloadStream.this,
    				  "Download already in progress...", Toast.LENGTH_SHORT)
    				    .show();
    			}
    		}catch(Exception e) {
    			Log.e(TAG, "error: " + e.toString());
    		}
			return true;
		}
    };
    
    private final MediaPlayer.OnBufferingUpdateListener mBufferListener =
		  new MediaPlayer.OnBufferingUpdateListener()
		{
			public void onBufferingUpdate(MediaPlayer mp, int percent)
			{
				Log.i(TAG, "onBufferingUpdate: percent=" + percent);
			}
		};

	private final MediaPlayer.OnPreparedListener mPreparedListener =
		  new MediaPlayer.OnPreparedListener()
		{
			public void onPrepared(MediaPlayer mp)
			{
				Log.d(TAG, "onPrepared called");
		        mVideoWidth = mPlayer.getVideoWidth();
		        mVideoHeight = mPlayer.getVideoHeight();
		        if (mVideoWidth != 0 && mVideoHeight != 0) {
		            mPreview.getHolder().setFixedSize(mVideoWidth, mVideoHeight);
		            mPlayer.start();
		        }

			}
		};


	private final MediaPlayer.OnCompletionListener mCompletionListener =
		  new MediaPlayer.OnCompletionListener()
		{
			public void onCompletion(MediaPlayer mp)
			{
				setPlaying(false);
				//startPlay(paths.get(1));
				
				Log.d(TAG, "onCompletion called");
			}
		};
		
		private final MediaPlayer.OnErrorListener mErrorListener =
			  new MediaPlayer.OnErrorListener()
			{
				public boolean onError(MediaPlayer mp, int what, int extra)
				{
					Log.i(TAG, "onError: what=" + what + ", extra=" + extra);

					mManager.stopDownload();

					if (mp.isPlaying() == true)
						mp.stop();

					mp.reset();
					playing = false;

					return true;
				}
			};
}
