package com.example.patrice.rerservation01;

import android.Manifest;
import android.app.Activity;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.PixelFormat;
import android.hardware.camera2.CameraDevice;
import android.os.Bundle;
import android.os.Environment;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.ScaleGestureDetector;
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.Date;
import java.util.Locale;
import android.hardware.Camera.PictureCallback;
import android.hardware.Camera.ShutterCallback;

//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


// issue de cam01 dans patoche_appli

public class capture01 extends AppCompatActivity implements SurfaceHolder.Callback
{

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

    SurfaceHolder surfaceHolder;
    boolean previewing = false;;

    SurfaceView surfaceView;

    private Bitmap bitmap;
    private ImageView photo;

    private static final int REQUEST = 200;

    protected CameraDevice cameraDevice;

    Button btn_startCameraPreview , btn_stopCameraPreview , btn_capture_photo ;

    private ScaleGestureDetector scaleGestureDetector;

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


        getSupportActionBar().setTitle("Capture");
        //getSupportActionBar().setLogo(R.drawable.user);
        //getSupportActionBar().setDisplayUseLogoEnabled(true);
        getSupportActionBar().setHomeButtonEnabled(true);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setDisplayShowHomeEnabled(true);

        photo = (ImageView) findViewById(R.id.photo);
        btn_startCameraPreview = (Button)findViewById(R.id.startcamerapreview);
        btn_stopCameraPreview = (Button)findViewById(R.id.stopcamerapreview);
        btn_capture_photo = (Button)findViewById(R.id.capture_photo);

        btn_startCameraPreview.setEnabled(true);
        btn_stopCameraPreview.setEnabled(false);
        btn_capture_photo.setEnabled(false);

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

        scaleGestureDetector = new ScaleGestureDetector( this, new MySimpleOnScaleGestureListener( surfaceView));

        /// permission
        if (ContextCompat.checkSelfPermission(capture01.this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED)
        {
            ActivityCompat.requestPermissions(capture01.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST);
        }

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


        btn_startCameraPreview.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;
                            btn_startCameraPreview.setEnabled(false);
                            btn_stopCameraPreview.setEnabled(true);
                            btn_capture_photo.setEnabled(true);
                        }
                        catch (IOException e)
                        {
                            e.printStackTrace();
                        }
                    }
                }
            }
        });

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


        btn_capture_photo.setOnClickListener(new Button.OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                takePicture();
            }
        });

    }

    /*************************************************************************/

    // pour le retour - inclus dans l'action bar ( < )
    @Override
    public boolean onOptionsItemSelected(MenuItem item)
    {
        switch (item.getItemId())
        {
            case android.R.id.home:
                this.finish();
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }

    /*************************************************************************/

    @Override
    public boolean onTouchEvent(MotionEvent event)
    {
        scaleGestureDetector.onTouchEvent(event);
        return true;
        //return super.onTouchEvent(event);
    }


    // http://android-innovation.blogspot.fr/2013/07/how-to-implement-pinch-and-pan-zoom-on.html
    // https://github.com/m-damavandi/ZoomableSurfaceView/blob/master/app/src/main/java/com/damavandi/zoomablesurfaceview/ZoomableSurfaceView.java

    //http://www.jayrambhia.com/blog/android-facedetection

    private class MySimpleOnScaleGestureListener   extends ScaleGestureDetector.SimpleOnScaleGestureListener{


        SurfaceView viewMyImage;

        float factor;

        public MySimpleOnScaleGestureListener( SurfaceView iv) {
            super();

            viewMyImage = iv;
        }

        @Override
        public boolean onScaleBegin(ScaleGestureDetector detector) {
            factor = 10.0f;
            return true;
            //return super.onScaleBegin(detector);
        }

        @Override
        public boolean onScale(ScaleGestureDetector detector) {

            float scaleFactor = detector.getScaleFactor() - 1;
            factor += scaleFactor;

            viewMyImage.setScaleX(factor);
            viewMyImage.setScaleY(factor);
            return true;
            //return super.onScale(detector);
        }
    }

    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(), "Capture avec la caméra", Toast.LENGTH_LONG).show();

            int w = surfaceView.getWidth();
            int l = photo.getHeight();

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

           // int _nWidth = bitmapPicture.getWidth();
           // int _nHeight = bitmapPicture.getHeight();

            bitmapPicture = Bitmap.createScaledBitmap(bitmapPicture, w, l, false);

            File sdcard_path = Environment.getExternalStorageDirectory();
            String filename = "pipoxxnow_semaine_direct.jpeg";


            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy_mm_dd_hh_mm_ss",   Locale.getDefault());

            filename = File.separator + "image_" + dateFormat.format(new Date()) + ".jpeg";


            File file = new File(sdcard_path, filename ); //"pipoxxnow_semaine_direct.jpeg");
            OutputStream fOut = null;
            try
            {
                fOut = new FileOutputStream(file);
                bitmapPicture.compress(Bitmap.CompressFormat.JPEG, 100, fOut);
            }
            catch (FileNotFoundException e)
            {
                e.printStackTrace();
            }

            try
            {
                fOut.flush();
                fOut.close();


                String imageInSD = Environment.getExternalStorageDirectory() + "/" + filename; // "/now_semaine_direct.png";  //"/sdcard/er.PNG";

                Bitmap bitmap = BitmapFactory.decodeFile(imageInSD);
                photo.setImageBitmap(bitmap);


                camera.stopPreview();
                camera.release();
                camera = null;
                previewing = false;
                btn_startCameraPreview.setEnabled(true);
                btn_stopCameraPreview.setEnabled(false);
                btn_capture_photo.setEnabled(false);



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

/*
            CameraManager manager = (CameraManager) getSystemService(Context.CAMERA_SERVICE);

            CameraCharacteristics characteristics = null;
            try
            {
                    characteristics = manager.getCameraCharacteristics(cameraDevice.getId());
                    Size[] jpegSizes = null;
                    if (characteristics != null)
                    {
                        jpegSizes = characteristics.get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP).getOutputSizes(ImageFormat.JPEG);
                    }
                    int width = 640;
                    int height = 480;
                    if (jpegSizes != null && 0 < jpegSizes.length)
                    {
                        width = jpegSizes[0].getWidth();
                        height = jpegSizes[0].getHeight();
                    }
            }

            catch (CameraAccessException 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)
    {

    }

    /******************************/

    private File openFileForImage()
    {
        File imageDirectory = null;
        String storageState = Environment.getExternalStorageState();
        if (storageState.equals(Environment.MEDIA_MOUNTED))
        {
            imageDirectory = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), "com.oreillyschool.android2.camera");

            if (!imageDirectory.exists() && !imageDirectory.mkdirs())
            {
                imageDirectory = null;
            }
            else
            {
                SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy_mm_dd_hh_mm", Locale.getDefault());

                return new File(imageDirectory.getPath() + File.separator + "image_" + dateFormat.format(new Date()) + ".png");
            }
        }
        return null;
    }

    private void saveImageToFile(File file)
    {
        Bitmap mCameraBitmap = null; // normalement l'affectation est faite dans le code

        if (mCameraBitmap != null)
        {
                FileOutputStream outStream = null;
                try
                {
                    outStream = new FileOutputStream(file);
                    if (!mCameraBitmap.compress(Bitmap.CompressFormat.PNG, 100, outStream))
                    {
                        Toast.makeText(capture01.this, "Unable to save image to file.", Toast.LENGTH_LONG).show();
                    }
                    else
                        {
                        Toast.makeText(capture01.this, "Saved image to: " + file.getPath(),  Toast.LENGTH_LONG).show();
                    }
                    outStream.close();

                }

                catch (Exception e)
                {
                    Toast.makeText(capture01.this, "Unable to save image to file.", Toast.LENGTH_LONG).show();
                }
        }
    }

    /********** END ********************/


}


