package edu.cs4730.VideoCap;

import java.io.IOException;

import android.app.Activity;
import android.media.MediaRecorder;
import android.os.Bundle;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.View.OnClickListener;

public class VideoCapture extends Activity implements OnClickListener, SurfaceHolder.Callback{
  MediaRecorder recorder;
  SurfaceHolder holder;
  boolean recording = false;
  String outputFile = "/sdcard/videoexample.mp4";
  
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        recorder = new MediaRecorder();
        initRecorder();

        SurfaceView cameraView = (SurfaceView) findViewById(R.id.CameraView);
        holder = cameraView.getHolder();
        holder.addCallback(this);
        holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);

        cameraView.setClickable(true);
        cameraView.setOnClickListener(this);
    }

    void initRecorder() {
      recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
      recorder.setVideoSource(MediaRecorder.VideoSource.DEFAULT);
      recorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
      recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
      recorder.setVideoEncoder(MediaRecorder.VideoEncoder.MPEG_4_SP);
      
      recorder.setOutputFile(outputFile);
      
    }
    @Override
    public void onClick(View v) {
      if (recording) {
        recorder.stop();
        recording = false;

        // Let's initRecorder so we can record again
        initRecorder();
        prepareRecorder();
      } else {
        recording = true;
        recorder.start();
      }


    }
    void prepareRecorder() {
      recorder.setPreviewDisplay(holder.getSurface());
      if (recorder != null) {
        try {
          recorder.prepare();
        } catch (IllegalStateException e) {
          Log.e("IllegalStateException", e.toString());
        } catch (IOException e) {
          Log.e("IOException", e.toString());
        }
      }
    }
    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width,  int height) {
      
    }

    @Override
    public void surfaceCreated(SurfaceHolder holder) {
      prepareRecorder();      
    }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {
      if (recording) {
        recorder.stop();
        recording = false;
    }
    recorder.release();
    finish();      
    }
}