package com.example.patrice.file01;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;

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

// http://www.vogella.com/tutorials/AndroidCamera/article.html

// https://mobikul.com/android-getting-image-camera-uploading-web-server-multipart-connection-type/

// https://www.androidhive.info/2013/09/android-working-with-camera-api/

// http://hmkcode.com/android-camera-taking-photos-camera/

public class MainActivity extends AppCompatActivity
{

    ArrayList<String> tab = new ArrayList<String>();

    private static final int REQUEST_CODE = 1;

    int REQUEST_TAKE_PHOTO = 1;


    private Bitmap bitmap;

    private int STORAGE_PERMISSION_CODE = 23;
    private ImageView imageView;
    private Button btn1;
    //private  Uri file;

    Uri outPutfileUri;

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        tab.add("Item1");
        tab.add("paul");
        tab.add("Remy");
        tab.add("vincent");
        tab.add("pipitron");

        btn1 = (Button) findViewById(R.id.button_image);

        imageView = (ImageView) findViewById(R.id.imageview);

        if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
            //btn1.setEnabled(false);
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE}, 0);
        }

        // Perform action on click
        btn1.setOnClickListener(new View.OnClickListener()
        {
            public void onClick(View v)
            {
                //create_file();
                takePicture();
            }
        });
    }

    public void takePicture()
    {
        //Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        //file = Uri.fromFile(getOutputMediaFile());
        //intent.putExtra(MediaStore.EXTRA_OUTPUT, file);
        //startActivityForResult(intent, 100);

        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);


        //File file = new File(Environment.getExternalStorageDirectory(), "MyPhoto.jpg");
        //outPutfileUri = Uri.fromFile(file);
        //intent.putExtra(MediaStore.EXTRA_OUTPUT, outPutfileUri);
        startActivityForResult(intent, REQUEST_TAKE_PHOTO);

    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data)
    {
        /*if (resultCode == RESULT_OK)
        {
            Bitmap bitmap = BitmapFactory.decodeFile(mCurrentPhotoPath);
            imgView.setImageBitmap(bitmap);
        }*/

        super.onActivityResult(requestCode, resultCode, data);

        if(this.REQUEST_TAKE_PHOTO == requestCode && resultCode == RESULT_OK)
        {
            Bitmap bitmap = (Bitmap)data.getExtras().get("data");

            String partFilename =  "photo_" + currentDateFormat() + ".jpg";
            storeCameraPhotoInSDCard(bitmap, partFilename);
            Bitmap mBitmap = getImageFileFromSDCard(partFilename);
            imageView.setImageBitmap(mBitmap);

        }
    }

    private String currentDateFormat()
    {

        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy_MM_dd_HH_mm_ss");
        String  currentTimeStamp = dateFormat.format(new Date());
        return currentTimeStamp;
    }

    private void storeCameraPhotoInSDCard(Bitmap bitmap, String partFilename)
    {
        File outputFile = new File(Environment.getExternalStorageDirectory() +"/" + partFilename);
        try
        {
            FileOutputStream fileOutputStream = new FileOutputStream(outputFile);
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fileOutputStream);
            fileOutputStream.flush();
            fileOutputStream.close();

        }

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

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


    private Bitmap getImageFileFromSDCard(String filename)
    {
        Bitmap bitmap = null;
        File imageFile = new File(Environment.getExternalStorageDirectory() + "/" +filename);

        try
        {
            FileInputStream fis = new FileInputStream(imageFile);
            bitmap = BitmapFactory.decodeStream(fis);
        }

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

        return bitmap;
    }




/*
    public void onActivityResult(int requestCode, int resultCode, Intent data)
    {
       /* if (requestCode == 100)

            if (resultCode == RESULT_OK)
            {
                imageView.setImageURI(file);
            }
        }*/
/*
        super.onActivityResult(requestCode, resultCode, data);

        InputStream stream = null;
        if (requestCode == REQUEST_CODE && resultCode == Activity.RESULT_OK)
        {

            try
            {
                stream = getContentResolver().openInputStream(data.getData());
            }
            catch (FileNotFoundException e)
            {
                e.printStackTrace();
            }
            bitmap = BitmapFactory.decodeStream(stream);

            imageView.setImageBitmap(bitmap);
        }
*/
/*
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == REQUEST_CODE && resultCode == RESULT_OK && data != null && data.getData() != null)
        {
            Uri uri = data.getData();

            Bundle extras = data.getExtras();

            // get bitmap
            Bitmap bitMap = (Bitmap) extras.get("data");
            imageView.setImageBitmap(bitMap);
         /*
            try
            {
                // Adding captured image in bitmap.
                bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), uri);
                // adding captured image in imageview.
                imageView.setImageBitmap(bitmap);

                Toast.makeText(this, outPutfileUri.toString(),Toast.LENGTH_LONG).show();
            }
            catch (IOException e)
            {
                e.printStackTrace();
            }*/
 /*       }

    }
*/

    private static File getOutputMediaFile()
    {
        File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory( Environment.DIRECTORY_PICTURES), "CameraDemo");

        if (!mediaStorageDir.exists()){
            if (!mediaStorageDir.mkdirs()){
                return null;
            }
        }

        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
        return new File(mediaStorageDir.getPath() + File.separator +   "IMG_"+ timeStamp + ".jpg");
    }
/*
    public void create_file()
    {

        try
        {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, STORAGE_PERMISSION_CODE);

            String path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/" + "mon_fichier.txt";
            File file = new File(path);

            if(!file.exists())
            {
                file.createNewFile();
            }

            String contenu = "Bonjour les petits !";

            FileWriter writer = new FileWriter(file, true); //True = Append to file, false = Overwrite
            writer.write(contenu + "\n");
            writer.close();

            Toast.makeText(MainActivity.this, "File Save!", Toast.LENGTH_LONG).show();

        }
        catch (IOException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
            Toast.makeText(MainActivity.this, "Failed!" + e.getMessage() ,  Toast.LENGTH_LONG).show();
        }

    }
*/
}
