package com.example.mynotepad.MenuFeatures.Pics.Camera;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.Toast;

import com.example.mynotepad.MenuFeatures.Utils;
import com.example.mynotepad.R;

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

public class CameraActivity extends AppCompatActivity {

    private ImageView switchCamera;
    private Button torch, flash, captureBtn;
    private SeekBar seekBarZoom;
    private static String filePath;
    private android.hardware.Camera mCamera;
    private final int RECORD_CAMERA_CODE = 130;

    @RequiresApi(api = Build.VERSION_CODES.M)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_camera_x);
        Utils.onActivityCreateSetTheme(this, getSupportActionBar());
        checkRuntimePermission();
        init();
        addListeners();
    }

    private void init() {
        captureBtn = findViewById(R.id.buttonCaptureImage);
        switchCamera = findViewById(R.id.switchCamera);
        flash = findViewById(R.id.buttonToggleFlash);
        torch = findViewById(R.id.buttonToggleTorch);
        seekBarZoom = findViewById(R.id.seekBarZoom);
        mCamera = getCameraInstance();
        CameraPreview mCameraPreview = new CameraPreview(this, mCamera);
        FrameLayout preview = findViewById(R.id.camera_preview);
        preview.addView(mCameraPreview);
        // backBtn = findViewById(R.id.cameraBackBtn);
    }

    private android.hardware.Camera getCameraInstance() {
        android.hardware.Camera camera = null;
        try {
            camera = android.hardware.Camera.open();
        } catch (Exception e) {
            // cannot get camera or does not exist
            Toast.makeText(this, "camera not found", Toast.LENGTH_LONG).show();
        }
        return camera;
    }

    private void addListeners() {
        captureBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onCaptureImage(v);
            }
        });
        switchCamera.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onSwitchCamera();
            }
        });
        flash.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onFlash();
            }
        });
        torch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onTorch();
            }
        });
        seekBarZoom.setOnSeekBarChangeListener(onSeekBarChange());
    }

    private void onCaptureImage(View v) {
        mCamera.takePicture(null, null, mPicture);
    }

    private SeekBar.OnSeekBarChangeListener onSeekBarChange() {
        return null;
    }

    private void onTorch() {
    }

    private void onFlash() {
    }

    private void onSwitchCamera() {
    }

    android.hardware.Camera.PictureCallback mPicture = new android.hardware.Camera.PictureCallback() {
        @Override
        public void onPictureTaken(byte[] data, android.hardware.Camera camera) {
            File pictureFile = getOutputMediaFile();
            filePath = pictureFile.getPath();

            if (pictureFile == null) {
                return;
            }
            try {
                FileOutputStream out = new FileOutputStream(pictureFile);//write on a file
                out.write(data);
                out.close();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }

            System.out.println("{{{{{{{{{{{{{{{}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}++++++++++               " + filePath);
            if (filePath != null) {
                Intent intent = new Intent();
                intent.putExtra("filePath", filePath);
                setResult(2, intent);
            }
            finish();
        }
    };

    public static File getOutputMediaFile() {
        //create a file to put pics in it
        File mediaStorageDir = new File(Environment.getExternalStorageDirectory(), "MyNotePad");
        if (!mediaStorageDir.exists()) {
            if (!mediaStorageDir.mkdirs()) {
                System.out.println("failed to create directory");
                return null;
            }
        }
        // Create a media file for pic
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
        File mediaFile = new File(mediaStorageDir.getPath() + File.separator + "IMG_" + timeStamp + ".jpg");
        return mediaFile;// return the pic file which we wanna write a pic on it
    }


    //check permissions
    @RequiresApi(api = Build.VERSION_CODES.M)
    private void checkRuntimePermission() {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED ||
                ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED ||
                ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            requestPermissions(new String[]{Manifest.permission.CAMERA, Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE}, RECORD_CAMERA_CODE);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == RECORD_CAMERA_CODE) {
            if (grantResults.length == 3 && grantResults[0] == PackageManager.PERMISSION_GRANTED && grantResults[1] == PackageManager.PERMISSION_GRANTED && grantResults[2]
                    == PackageManager.PERMISSION_GRANTED) {
                Toast.makeText(this, "accepted", Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(this, "You must give permissions to use this app. App is exiting.", Toast.LENGTH_SHORT).show();
                finish();
            }
        }
    }
}


