package tools;

import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.View;

import androidx.core.content.FileProvider;

import java.io.File;

import kz.istt.locust.BuildConfig;
import kz.istt.locust.LocustHealthActivity;

public class OnClickListenerImage implements View.OnClickListener {

    public int requestCode;
    public Context context;

    public OnClickListenerImage(Context context, int requestCode){
        this.context=context;
        this.requestCode=requestCode;
    }

    @Override
    public void onClick(View view) {
        // Создаём папку если её нет
        File directory = new File(Environment.getExternalStorageDirectory() + File.separator + "Pictures" + File.separator + "Locust");
        directory.mkdirs();

        String tmp_ImageName = "locust_" + (System.currentTimeMillis() / 1000L) + ".jpg";

        // Сохраняем имя файла в SharedPreferences
        SharedPreferences preferences = context.getSharedPreferences("CommonPrefs", Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = preferences.edit();
        editor.putString("IMAGE_NAME", tmp_ImageName);
        editor.apply();

        File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/Pictures/Locust/" + tmp_ImageName);

        Uri mImageUri;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
            mImageUri = FileProvider.getUriForFile(context, BuildConfig.APPLICATION_ID + ".provider",file);
        else
            mImageUri = Uri.fromFile(file);

        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, mImageUri);
        intent.putExtra(MediaStore.EXTRA_MEDIA_TITLE, tmp_ImageName);
        ((Activity) context).startActivityForResult(intent, requestCode);
    }
}
