package com.app.broadcastvideo_115;

import java.io.File;
import java.io.IOException;

import net.HttpVideoUploader;
import net.HttpVideoUploader.Uploader;
import android.app.Activity;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.media.MediaRecorder;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.Window;
import android.view.MenuItem.OnMenuItemClickListener;

public class BroadcastActivity extends Activity{
	public static final String TAG = "BroadcastActivity";
	private BroadcastPreview bPreview;
	private MediaRecorder recorder;
	private boolean recording = false;
	File mSampleFile = null;
	private int eid;
	HttpVideoUploader mUploader = new HttpVideoUploader(this);
	Uploader u = null;
	 
	static final String SAMPLE_PREFIX = "recording_mp4";
    static final String SAMPLE_EXTENSION = ".3gp"; 
	
	@Override
    public void onCreate(Bundle savedInstanceState) {
         super.onCreate(savedInstanceState);
         requestWindowFeature(Window.FEATURE_NO_TITLE);
         setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
         bPreview = new BroadcastPreview(this);
         setContentView(bPreview);
         recorder = new MediaRecorder();
         eid = 1;
    } 
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuItem start = menu.add("Start Recording");
		MenuItem stop = menu.add("Stop Recording");
		start.setOnMenuItemClickListener(start_recording);
		stop.setOnMenuItemClickListener(stop_recording);
		return super.onCreateOptionsMenu(menu);
	}
	
	private void config() {
		recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
        recorder.setVideoSource(MediaRecorder.VideoSource.DEFAULT);
        recorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
        recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
        recorder.setVideoEncoder(MediaRecorder.VideoEncoder.MPEG_4_SP);
	}
	
	private final OnMenuItemClickListener start_recording = new OnMenuItemClickListener() {

		
		public boolean onMenuItemClick(MenuItem item) {
			u = mUploader.startUpload(eid);
			autoSaver.start();

			return true;
		}
    };
    
    private final OnMenuItemClickListener stop_recording = new OnMenuItemClickListener(){

		
		public boolean onMenuItemClick(MenuItem item) {
			if (recording) {
				autoSaver.stop();
				recorder.stop();
				recorder.release();
                addToDB();
                recording = false;
                //showDialog(UPLOAD_ASKING);
                //finish();
            }
			return true;
		}
    };
    
    private Thread autoSaver = new Thread() {
    	public void run() {
    		int i = 0;
    		while(true) {
    			config();
    			
    		          File sampleDir = Environment.getExternalStorageDirectory();
    		         
    		          try { mSampleFile = File.createTempFile("videomp4" + i, SAMPLE_EXTENSION, sampleDir);
    		          } catch (IOException e) {
    		              Log.e(TAG,"sdcard access error");
    		              //return false;
    		          }
    	      
    			recorder.setOutputFile(mSampleFile.getAbsolutePath());
    			recorder.setPreviewDisplay(bPreview.getHolder().getSurface());
    	        if (bPreview != null) {
    	             try {
    	            	 recorder.prepare();
    	             } catch (IllegalStateException e) {
    	                  Log.e("IllegalStateException", e.toString());
    	             } catch (IOException e) {
    	                  Log.e("IOException", e.toString());
    	             }
    	        }
    			recording = true;
    			//camcorderPreview.getRecorder().setOutputFile(mSampleFile.getAbsolutePath());
    			recorder.start();
    			try {
					Thread.sleep(5000);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				recorder.stop();
				addToDB();
				u.addVideoPath(mSampleFile.getAbsolutePath());
				i++;
    		}
    	}
    };
    
    protected void addToDB() {
        ContentValues values = new ContentValues(3);
        long current = System.currentTimeMillis();
            
        values.put(MediaStore.Audio.Media.TITLE, mSampleFile.getName());
        values.put(MediaStore.Audio.Media.DATE_ADDED, (int) (current / 1000));
        values.put(MediaStore.Audio.Media.MIME_TYPE, "video/3gpp");
        values.put(MediaStore.Audio.Media.DATA, mSampleFile.getAbsolutePath());
        ContentResolver contentResolver = getContentResolver();  
        
        Uri base = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
        Uri newUri = contentResolver.insert(base, values);

        sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, newUri));
        Log.i(TAG, "MEDIA SCANNED");
    }

}
