package com.appli.camera;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Camera;
import android.graphics.PixelFormat;
import android.graphics.Rect;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;

import android.content.Context;
import android.view.SurfaceHolder;
import android.view.SurfaceView;

import android.graphics.Rect;
import android.hardware.Camera.AutoFocusCallback;
import android.hardware.Camera.Face;
import android.hardware.Camera.FaceDetectionListener;
import android.hardware.Camera.Parameters;
import android.hardware.Camera.PictureCallback;
import android.hardware.Camera.ShutterCallback;


import java.io.IOException;

//import android.hardware.Camera;
import static android.provider.MediaStore.Files.FileColumns.MEDIA_TYPE_IMAGE;
import static com.appli.patoche.R.id.photo;
import static java.security.AccessController.getContext;

import com.appli.patoche.R;

//https://stuff.mit.edu/afs/sipb/project/android/docs/guide/topics/media/camera.html

// https://github.com/khetiyachintan/CameraPreview/tree/master/CameraPreview/src/pkg/android/chintan/khetiya/cp


public class cam01 extends Activity implements SurfaceHolder.Callback
{

    //Camera camera;
    android.hardware.Camera camera;

    SurfaceView surfaceView;
    SurfaceHolder surfaceHolder;
    boolean previewing = false;;

    String stringPath = "/sdcard/samplevideo.3gp";

    private static final int TAKE_PICTURE = 1;

    private Bitmap bitmap;
    private ImageView photo;


    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.cam01_layout);

        //setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);

        photo = (ImageView) findViewById(R.id.photo);

        Button buttonStartCameraPreview = (Button)findViewById(R.id.startcamerapreview);
        Button buttonStopCameraPreview = (Button)findViewById(R.id.stopcamerapreview);

        getWindow().setFormat(PixelFormat.UNKNOWN);
        surfaceView = (SurfaceView)findViewById(R.id.surfaceview);
        surfaceHolder = surfaceView.getHolder();
        surfaceHolder.addCallback(this);
        surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);

        camera = android.hardware.Camera.open();


        android.hardware.Camera.Parameters parametro = camera.getParameters(); // WORKS OK
        //parametro.setFlashMode("on"); // WORKS OK
        //camera.setParameters(parametro); // WORKS OK


        if (parametro.getMaxNumMeteringAreas() > 0){ // check that metering areas are supported
            ArrayList<android.hardware.Camera.Area> meteringAreas = new ArrayList<android.hardware.Camera.Area>();

            Rect areaRect1 = new Rect(-100, -100, 100, 100);    // specify an area in center of image
            meteringAreas.add(new android.hardware.Camera.Area(areaRect1, 600)); // set weight to 60%
            Rect areaRect2 = new Rect(800, -1000, 1000, -800);  // specify an area in upper right of image
            meteringAreas.add(new android.hardware.Camera.Area(areaRect2, 400)); // set weight to 40%
            parametro.setMeteringAreas(meteringAreas);


        }

        camera.setParameters(parametro);


        buttonStartCameraPreview.setOnClickListener(new Button.OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                if(!previewing){
                    camera = android.hardware.Camera.open();
                    if (camera != null)
                    {
                        try
                        {
                            camera.setPreviewDisplay(surfaceHolder);
                            camera.startPreview();
                            previewing = true;
                        }
                        catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        });

        buttonStopCameraPreview.setOnClickListener(new Button.OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                if(camera != null && previewing)
                {
                    camera.stopPreview();
                    camera.release();
                    camera = null;
                    previewing = false;
                }
            }
        });


    }


    // http://android-er.blogspot.fr/2010/12/implement-takepicture-function-of.html

    public void onClick(View View)
    {


        //Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        //startActivityForResult(intent, TAKE_PICTURE);

        //camera = android.hardware.Camera.open();


/*

        ShutterCallback shutterCallback = new ShutterCallback()
        {
            @Override
            public void onShutter()
            {
                // faire queleque chose lorsque l'obturateur se ferme
            }
        };

        PictureCallback raxCallback = new PictureCallback()
        {
            @Override
            public void onPictureTaken(byte[] data, android.hardware.Camera camera)
            {
                // faire quelque chose de l'image brute
            }
        };

        PictureCallback jpegCallback = new PictureCallback()
        {
            @Override
            public void onPictureTaken(byte[] data, android.hardware.Camera camera)
            {
                // sauvegarde l'image jpeg sur la carte SD
                FileOutputStream outstream = null;

                try
                {
                    outstream = new FileOutputStream("/sdcard/test.jpg");
                    outstream.write(data);
                    outstream.close();

                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        };

*/

       // camera.takePicture(shutterCallback, raxCallback,  jpegCallback);

        // camera.takePicture(   android.hardware.Camera.ShutterCallback                , rawCallback, jpegCallback);


       // camera.takePicture(   android.hardware.Camera.ShutterCallback                , rawCallback, jpegCallback);

        takePicture();

        //camera.takePicture(myShutterCallback,  myPictureCallback_RAW, myPictureCallback_JPG);

    }

/*
    ShutterCallback myShutterCallback = new ShutterCallback()
    {

        @Override
        public void onShutter() {


        }};

    PictureCallback myPictureCallback_RAW = new PictureCallback()
    {
        @Override
        public void onPictureTaken(byte[] data, android.hardware.Camera camera)
        {

        }

      };

    PictureCallback myPictureCallback_JPG = new PictureCallback()
    {
        @Override
        public void onPictureTaken(byte[] data, android.hardware.Camera camera)
        {
            Bitmap bitmapPicture  = BitmapFactory.decodeByteArray(data, 0, data.length);

            File sdcard_path = Environment.getExternalStorageDirectory();
            File file = new File(sdcard_path, "direct.png");
            OutputStream fOut = null;
            try
            {
                fOut = new FileOutputStream(file);
                bitmapPicture.compress(Bitmap.CompressFormat.PNG, 100, fOut);
            }
            catch (FileNotFoundException e)
            {
                e.printStackTrace();
            }

            try
            {
                fOut.flush();
                fOut.close();
            }
            catch (IOException e)
            {
                e.printStackTrace();
            }
        }
    };
*/

    // http://book2s.com/java/api/android/hardware/camera/takepicture-3.html

    // android camera takepicture shuttercallback

    //http://codetoart.com/android-using-camera-api/

    // http://androidbiancheng.blogspot.fr/2010/12/androidcameratakepicture.html
    private void takePicture()
    {
        camera.takePicture(shutterCallback, rawCallback, jpegCallback);
    }

    ShutterCallback shutterCallback = new ShutterCallback()
    {  // aprés le déclenchement de l'opturateur
        public void onShutter()
        {

        }
    };

    PictureCallback rawCallback = new PictureCallback()
    {   //  traitement RAW
        @Override
        public void onPictureTaken(byte[] data, android.hardware.Camera camera)
        {

        }
    };

    PictureCallback jpegCallback = new PictureCallback()
    {   // traitement jpeg
        public void onPictureTaken(byte[] data, android.hardware.Camera camera)
        {
            Toast.makeText(getApplicationContext(), "msg msg", Toast.LENGTH_LONG).show();

            Bitmap bitmapPicture  = BitmapFactory.decodeByteArray(data, 0, data.length);

            File sdcard_path = Environment.getExternalStorageDirectory();
            File file = new File(sdcard_path, "1semaine_direct.png");
            OutputStream fOut = null;
            try
            {
                fOut = new FileOutputStream(file);
                bitmapPicture.compress(Bitmap.CompressFormat.PNG, 100, fOut);
            }
            catch (FileNotFoundException e)
            {
                e.printStackTrace();
            }

            try
            {
                fOut.flush();
                fOut.close();
            }
            catch (IOException e)
            {
                e.printStackTrace();
            }
        }
    };


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data)
    {

        if (requestCode == TAKE_PICTURE && resultCode == Activity.RESULT_OK)
        {
            Bundle extras = data.getExtras();
            bitmap = (Bitmap) extras.get("data");
            photo.setImageBitmap(bitmap);

            File sdcard_path = Environment.getExternalStorageDirectory();
            File file = new File(sdcard_path, "aaa.png");
            OutputStream fOut = null;
            try
            {
                fOut = new FileOutputStream(file);
                bitmap.compress(Bitmap.CompressFormat.PNG, 100, fOut);
            }
            catch (FileNotFoundException e)
            {
                e.printStackTrace();
            }

            try
            {
                fOut.flush();
                fOut.close();
            }
            catch (IOException e)
            {
                e.printStackTrace();
            }

        }
    }

    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width, int height)
    {

    }

    @Override
    public void surfaceCreated(SurfaceHolder holder)
    {

    }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder)
    {

    }
}


/*
public class cam01 extends AppCompatActivity
{
    private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100;

    public static final int MEDIA_TYPE_IMAGE = 1;
    public static final int MEDIA_TYPE_VIDEO = 2;

    private Uri fileUri;

    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        // create Intent to take a picture and return control to the calling application
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

        fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE); // create a file to save the image
        intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri); // set the image file name

        // start the image capture Intent
        startActivityForResult(intent, CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE);
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data)
    {
        if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE)
        {
            if (resultCode == RESULT_OK)
            {
                // Image captured and saved to fileUri specified in the Intent
                Toast.makeText(this, "Image saved to:\n" +   data.getData(), Toast.LENGTH_LONG).show();
            } else if (resultCode == RESULT_CANCELED) {
                // User cancelled the image capture
            } else {
                // Image capture failed, advise user
            }
        }


    }




    /** Create a file Uri for saving an image or video */
/*
    private static Uri getOutputMediaFileUri(int type)
    {
        return Uri.fromFile(getOutputMediaFile(type));
    }


    /** Create a File for saving an image or video */
/*
    private static File getOutputMediaFile(int type)
    {
        // To be safe, you should check that the SDCard is mounted
        // using Environment.getExternalStorageState() before doing this.

        File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(
                Environment.DIRECTORY_PICTURES), "MyCameraApp");
        // This location works best if you want the created images to be shared
        // between applications and persist after your app has been uninstalled.

        // Create the storage directory if it does not exist
        if (! mediaStorageDir.exists()){
            if (! mediaStorageDir.mkdirs()){
                Log.d("MyCameraApp", "failed to create directory");
                return null;
            }
        }

        // Create a media file name
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
        File mediaFile;
        if (type == MEDIA_TYPE_IMAGE)
        {
            mediaFile = new File(mediaStorageDir.getPath() + File.separator +
                    "IMG_"+ timeStamp + ".jpg");
        }
        else if(type == MEDIA_TYPE_VIDEO)
        {
            mediaFile = new File(mediaStorageDir.getPath() + File.separator +
                    "VID_"+ timeStamp + ".mp4");
        }
        else {
            return null;
        }

        return mediaFile;
    }
}


/*
class ImageSurfaceView extends SurfaceView implements SurfaceHolder.Callback {

    private Camera camera;
    private SurfaceHolder surfaceHolder;

    public ImageSurfaceView(Context context, Camera camera) {
        super(context);
        this.camera = camera;
        this.surfaceHolder = getHolder();
        this.surfaceHolder.addCallback(this);
    }

    @Override
    public void surfaceCreated(SurfaceHolder holder) {
        try {
            this.camera.setPreviewDisplay(holder);
            this.camera.startPreview();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {

    }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {
        this.camera.stopPreview();
        this.camera.release();
    }
}

*/