/****************************************************************************
*
* ChoicesActivity - deals with letting user choose the background for the canvas
*
* Programmer: Annicka Rabida, May 2021
* 
***************************************************************************/
package com.example.paintingphotos;

import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.FileProvider;

import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.ImageDecoder;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class ChoicesActivity extends AppCompatActivity {
    Bitmap selectedBitmap = MainActivity.selectedBitmap;
    public static boolean useBlank = true;
    public static boolean usedCamera = false;
    public static String currentPhotoPath;
    public static String picturePath;
    private final int CAMERA = 1;
    private final int CAMERA_ROLL = 2;
    private final int BLANK = 3;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_choices);
        Log.w("choices MSG", "beginning bitmap: " + selectedBitmap);
    }

    public void onClickCameraRoll(View v) {
        useBlank = false;
        usedCamera = false;
        Intent intent = new Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        startActivityForResult(intent, CAMERA_ROLL);
        Log.w("choices MSG", "button clicked");
    }

    public void onClickCamera(View v){
        useBlank = false;
        usedCamera = true;
        dispatchTakePictureIntent();
    }
    public void onClickBlank(View v) {
        useBlank = true;
        Intent canvasIntent = new Intent(this, CanvasActivity.class);
        startActivityForResult(canvasIntent, BLANK);
        this.finish();
    }

    @RequiresApi(api = Build.VERSION_CODES.P)
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == CAMERA) {
                File file = new File(currentPhotoPath);
                Bitmap bitmap = null;
                try {
                    bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), Uri.fromFile(file));
                } catch (IOException e) {
                    e.printStackTrace();
                }
                if (bitmap != null) {
                    Log.w("MSG choices", "image width: " + bitmap.getWidth());
                    Log.w("MSG choices", "image height: " + bitmap.getHeight());
                    MainActivity.selectedBitmap = bitmap;
                    Log.w("choices MSG", "bitmap from camera: " + selectedBitmap);
                    Intent canvasIntent = new Intent(this, CanvasActivity.class);
                    startActivity(canvasIntent);
                    this.finish();
                }
            } else if (requestCode == CAMERA_ROLL) {
                    Log.w("MSG choices", "uri: " + data.getData());
                    Uri selectedImage = data.getData();
                    String[] filePath = {MediaStore.Images.Media.DATA};
                    Cursor c = getContentResolver().query(selectedImage, filePath, null, null, null);
                    c.moveToFirst();
                    int columnIndex = c.getColumnIndex(filePath[0]);
                    picturePath = c.getString(columnIndex);
                    c.close();
                    Log.w("MSG choices", "picturePath: " + picturePath);
                    Bitmap thumbnail;
                    ImageDecoder.Source source = ImageDecoder.createSource(getApplicationContext().getContentResolver(), selectedImage);
                    source = ImageDecoder.createSource(this.getContentResolver(), selectedImage);
                    try {
                        Bitmap t  = ImageDecoder.decodeBitmap(source);
                        thumbnail = t.copy(Bitmap.Config.ARGB_8888, true);
                        Log.w("MSG choices", "bitmap: " + thumbnail);
                        MainActivity.selectedBitmap = thumbnail;
                        Log.w("MSG choices", "image width: " + thumbnail.getWidth());
                        Log.w("MSG choices", "image height: " + thumbnail.getHeight());
                        Log.w("MSG choices", "global bitmap: " + selectedBitmap);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    Log.w("MSG choices", picturePath + "");
                    Intent canvasIntent = new Intent(this, CanvasActivity.class);
                    startActivity(canvasIntent);
                    this.finish();
                }
            }
        }

    private File createImageFile() throws IOException {
        /** Create an image file name **/
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
        String imageFileName = "JPEG_" + timeStamp + "_";
        File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
        File image = File.createTempFile(
                imageFileName,  /** prefix **/
                ".jpg",  /** suffix **/
                storageDir      /** directory **/
        );
        /** Save a file: path for use with ACTION_VIEW intents **/
        currentPhotoPath = image.getAbsolutePath();
        return image;
    }

    private void dispatchTakePictureIntent() {
        Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        /** Ensure that there's a camera activity to handle the intent **/
        if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
            /** Create the File where the photo should go **/
            File photoFile = null;
            try {
                photoFile = createImageFile();
            } catch (IOException ex) {
                // Error occurred while creating the File
            }
            /** Continue only if the File was successfully created **/
            if (photoFile != null) {
                Uri photoURI = FileProvider.getUriForFile(this, "com.example.android.fileprovider", photoFile);
                takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
                startActivityForResult(takePictureIntent, CAMERA);
            }
        }
    }
}