package com.example.mynotepad.MenuFeatures.Pics;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.fragment.app.Fragment;

import android.provider.MediaStore;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.example.mynotepad.Dialogs.AddTxtToPicsDialog.AddTextToPicDialog;
import com.example.mynotepad.Dialogs.AddTxtToPicsDialog.OnSavePicListenerClick;
import com.example.mynotepad.MainActivity;
import com.example.mynotepad.MenuFeatures.AllNotes.DataBase.PicsEntity;
import com.example.mynotepad.MenuFeatures.Pics.Camera.CameraActivity;
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.io.InputStream;
import java.io.OutputStream;

import static com.example.mynotepad.MainActivity.noteDataBase;
import static com.example.mynotepad.MenuFeatures.Pics.Camera.CameraActivity.getOutputMediaFile;

public class ChoosingPicsFragment extends Fragment {

    private LinearLayout camera, gallery;
    private String newFilePath;
    private ConstraintLayout constraintLayout;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        ((PicsActivity) getActivity()).getSupportActionBar().setTitle("Choose Pic");
        return inflater.inflate(R.layout.fragment_choosing_pics, container, false);
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        init(view);
        setBg(Utils.sTheme);
        addListeners();
    }

    private void setBg(String sTheme) {
        switch (sTheme) {
            case "dark":
                constraintLayout.setBackgroundResource(R.drawable.main_bg_dark);
                break;
            case "bright":
                constraintLayout.setBackgroundResource(R.drawable.main_bg_bright);
                break;
        }
    }

    private void init(View view) {
        camera = view.findViewById(R.id.cameraBtn);
        gallery = view.findViewById(R.id.galleryBtn);
        constraintLayout = view.findViewById(R.id.constrainLayout);
    }

    private void addListeners() {
        camera.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivityForResult(new Intent(getActivity(), CameraActivity.class), 2);
            }
        });

        gallery.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                startActivityForResult(intent, 1);
            }
        });
    }

    @RequiresApi(api = Build.VERSION_CODES.KITKAT)
    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        newFilePath = "";
        if (data != null) {
            if (requestCode == 1) {// get image from gallery

                File pictureFile = getOutputMediaFile();
                if (pictureFile == null) { return; }
                InputStream stream = null;
                try {
                    newFilePath = pictureFile.getPath();
                    BitmapFactory.decodeStream(getActivity().getContentResolver().openInputStream(data.getData()));
                    stream = getActivity().getContentResolver().openInputStream(data.getData());
                    try (OutputStream output = new FileOutputStream(pictureFile)) {
                        byte[] buffer = new byte[4 * 1024]; // or other buffer size
                        int read;

                        while ((read = stream.read(buffer)) != -1) {
                            output.write(buffer, 0, read);
                        }

                        output.flush();
                    }
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }

                showDialogOnResult(BitmapFactory.decodeFile(pictureFile.getAbsolutePath()));
            } else if (requestCode == 2) {// get image from camera
                newFilePath = data.getStringExtra("filePath");
                File imgFile = new File(newFilePath);
                if (imgFile.exists()) {
                    showDialogOnResult(BitmapFactory.decodeFile(imgFile.getAbsolutePath()));
                }
            }
        }
    }

    private void showDialogOnResult(final Bitmap bitmap) {
        //show dialog to save pic with note
        AddTextToPicDialog addTextToPicDialog = new AddTextToPicDialog();
        addTextToPicDialog.showAddTxtDialog(getActivity(), bitmap);
        addTextToPicDialog.setOnSavePicListenerClick(new OnSavePicListenerClick() {
            @Override
            public void saveClicked(String editTextTxt) {
                PicsEntity picsEntity = new PicsEntity(newFilePath, editTextTxt);
                noteDataBase.picsDao().insertPicsNote(picsEntity);
            }
        });
    }
}