package com.netfluke.sergey.simplecam;

/** Simple Picture example from
  *    https://developer.android.com/training/camera/photobasics.html
  */

import android.content.Intent;
import android.graphics.Bitmap;
import android.hardware.Camera;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class MainActivity extends AppCompatActivity {

     final int REQUEST_IMAGE_CAPTURE = 1;
     private ImageView imageView;
     Bitmap bitmap;
     
     @Override
     protected void onCreate(Bundle savedInstanceState) {
          super.onCreate(savedInstanceState);
          setContentView(R.layout.activity_main);
          
          imageView = findViewById(R.id.image_view);
          if( bitmap != null)
               imageView.setImageBitmap(bitmap);
     }
     
     public void camButtonClicked(View v){
          
          Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
          
          // This is supposed to use front camera. Instead, it crashed cam app.
          //takePictureIntent.putExtra("android.intent.extras.CAMERA_FACING",
          //        android.hardware.Camera.CameraInfo.CAMERA_FACING_FRONT);
          
          if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
               startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
          }
     }
     
     // Comment out the following two functions and see what happens
     //   with the ImageView after you flip the phone's orientation.
     @Override
     protected void onSaveInstanceState(Bundle outState) {
          super.onSaveInstanceState(outState);
          // save the bitmap
          Log.d("STATE", "onSaveState");
          outState.putParcelable("IMG", bitmap);
     }
     
     // see above
     @Override
     protected void onRestoreInstanceState(Bundle savedInstanceState) {
          super.onRestoreInstanceState(savedInstanceState);
          Log.d("STATE", "onRestoreState");
          bitmap = savedInstanceState.getParcelable("IMG");
          imageView.setImageBitmap(bitmap);
     }
     
     @Override
     protected void onActivityResult(int requestCode, int resultCode, Intent data) {
          if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
               Bundle extras = data.getExtras();
               bitmap = (Bitmap) extras.get("data");
               imageView.setImageBitmap(bitmap);
          }
     }
}
