package com.example.patrice.rerservation01;

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.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.PixelFormat;
import android.hardware.Camera;
import android.os.Bundle;
import android.os.Environment;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
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 static android.Manifest.permission.CAMERA;
import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE;

public class camera_capture_image extends Activity implements SurfaceHolder.Callback
{
    Camera camera;
    SurfaceView surfaceView;
    SurfaceHolder surfaceHolder;
    boolean previewing = false;;

    private Bitmap bitmap;
    private ImageView photo;

    private static final int REQUEST = 200;
    public static final int RequestPermissionCode = 1;
    String filename = "";

    String code = "";


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

        Intent intent = getIntent();
        Bundle b = getIntent().getExtras();
        code = b.getString("code", "");

        Button buttonStartCameraPreview = (Button)findViewById(R.id.startcamerapreview);
        Button buttonStopCameraPreview = (Button)findViewById(R.id.stopcamerapreview);
        Button buttonCapturePhoto = (Button)findViewById(R.id.capture_photo);
        photo = (ImageView) findViewById(R.id.photo);


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

/*          OK pour la camera

        if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED)
        {
            if (ActivityCompat.shouldShowRequestPermissionRationale(work01.this, Manifest.permission.CAMERA))
            {
                AlertDialog.Builder alertBuilder = new AlertDialog.Builder(this);
                alertBuilder.setCancelable(true);
                alertBuilder.setTitle("Permission necessary");
                alertBuilder.setMessage("CAMERA is necessary");

                alertBuilder.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener()
                {
                    //@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
                    public void onClick(DialogInterface dialog, int which)
                    {
                        ActivityCompat.requestPermissions(work01.this, new String[]{Manifest.permission.CAMERA}, REQUEST);
                    }
                });

                AlertDialog alert = alertBuilder.create();
                alert.show();
            } else {
                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA}, REQUEST);
            }
        }
*/

        if(!checkPermission())
        {
            requestPermission();

        }

        buttonStartCameraPreview.setOnClickListener(new Button.OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                if(!previewing)
                {
                    camera = 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;
                }
            }});

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

    }

    @Override
    public void onBackPressed()
    {
        Intent intent=new Intent();
        intent.putExtra("TAG_FILENAME",filename);
        setResult(150,intent);
        finish();
        Toast.makeText(camera_capture_image.this,"Bye...",Toast.LENGTH_LONG).show();

    }

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

    public boolean checkPermission()
    {
        int check_camera = ContextCompat.checkSelfPermission(getApplicationContext(), WRITE_EXTERNAL_STORAGE);
        int check_write_storage = ContextCompat.checkSelfPermission(getApplicationContext(), CAMERA);

        return ( check_camera == PackageManager.PERMISSION_GRANTED && check_write_storage == PackageManager.PERMISSION_GRANTED ) ;
    }

    private void requestPermission()
    {
        ActivityCompat.requestPermissions(camera_capture_image.this, new String[]{WRITE_EXTERNAL_STORAGE, CAMERA}, RequestPermissionCode);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults)
    {
        switch (requestCode)
        {
            case RequestPermissionCode:
                if (grantResults.length > 0)
                {
                    boolean StoragePermission = grantResults[0] == PackageManager.PERMISSION_GRANTED;
                    boolean CameraPermission = grantResults[1] == PackageManager.PERMISSION_GRANTED;
                    if (StoragePermission && CameraPermission)
                    {
                        Toast.makeText(camera_capture_image.this, "Permission Granted", Toast.LENGTH_LONG).show();
                    }
                    else
                    {
                        Toast.makeText(camera_capture_image.this,"Permission Denied",Toast.LENGTH_LONG).show();
                    }
                }

                break;
        }
    }

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

    private void takePicture()
    {
        camera.takePicture(shutterCallback, rawCallback, jpegCallback);
    }

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

        }
    };

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

        }
    };

    Camera.PictureCallback jpegCallback = new Camera.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();
            filename = "pipoxxnow_semaine_direct.jpeg";


            SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy_hh:mm:ss",   Locale.getDefault());

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

            filename = File.separator + code + ".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();

                // affichage
                String imageInSD = Environment.getExternalStorageDirectory() + "/" + filename; // "/now_semaine_direct.png";  //"/sdcard/er.PNG";
                imageInSD = Environment.getExternalStorageDirectory() + "/" + code + ".jpeg"; // "/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();
            }

        }
    };



    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width, int height)
    {
        // TODO Auto-generated method stub

    }

    @Override
    public void surfaceCreated(SurfaceHolder holder)
    {
        // TODO Auto-generated method stub

    }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder)
    {
        // TODO Auto-generated method stub

    }
}