package com.study.sketch.learning.fragment;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import androidx.activity.result.ActivityResultCallback;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.GridLayoutManager;

import com.ad.maxlibrary.MaxManager;
import com.ad.maxlibrary.onAdAfterAction;
import com.study.sketch.learning.R;
import com.study.sketch.learning.SketchingApp;
import com.study.sketch.learning.database.BeanImport;
import com.study.sketch.learning.database.MyDb;
import com.study.sketch.learning.databinding.FragmentGalleryBinding;
import com.study.sketch.learning.item.AdapterGallery;
import com.study.sketch.learning.item.SpacingItemDecoration;
import com.study.sketch.learning.manager.Common;

import java.io.File;
import java.util.List;
import java.util.Map;

public class FragmentGallery extends Fragment   {

    private FragmentGalleryBinding binding;


    private String[] permissions;

    private AdapterGallery adapterGallery;
    private ActivityResultLauncher<Intent> intentActivityResultLauncher;
    private ActivityResultLauncher<String[]> permissionsLauncher;
    public FragmentGallery() {

    }

    public static FragmentGallery newInstance() {
        FragmentGallery fragment = new FragmentGallery();
        Bundle args = new Bundle();
        fragment.setArguments(args);
        return fragment;
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        binding = FragmentGalleryBinding.inflate(getLayoutInflater());
        onInit();

        return binding.getRoot();
    }


    private void onInit() {

        binding.loading.setVisibility(View.VISIBLE);
        loadImport();
        binding.btnImport.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                MaxManager.startShowMaxAd(requireActivity(), new onAdAfterAction() {
                    @Override
                    public void onAction() {
                        checkPermission();
                    }
                });

            }
        });

        permissionsLauncher = registerForActivityResult(
                new ActivityResultContracts.RequestMultiplePermissions(),
                new ActivityResultCallback<Map<String, Boolean>>() {
                    @Override
                    public void onActivityResult(Map<String, Boolean> result) {
                        Boolean isGranted = true;
                        for (Map.Entry<String, Boolean> entry : result.entrySet()) {
                            String permission = entry.getKey();
                            isGranted = entry.getValue();
                            if(!entry.getValue()){
                                isGranted = false;
                            }
                        }
                        if (isGranted) {
                            takeGallery();
                        }else {
                            Toast.makeText(requireContext(),   " Permission denied", Toast.LENGTH_SHORT).show();
                        }
                    }
                }
        );
        intentActivityResultLauncher = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), result -> {
            if (result.getResultCode() == Activity.RESULT_OK && result.getData() != null) {
                Uri imageUri = result.getData().getData();
                if (imageUri != null) {
                    binding.loading.setVisibility(View.VISIBLE);
                    double uriFileSize = Common.getUriFileSize(requireContext(), imageUri);
                    Log.d(SketchingApp.TAG, "------uriFileSize-----" + uriFileSize + "--Mb");
                    if (uriFileSize >= 5) {
                        binding.loading.setVisibility(View.GONE);
                        Toast.makeText(requireContext(), getString(R.string.import_im_too_big), Toast.LENGTH_SHORT).show();
                        return;
                    }
                    String lastPathSegment = imageUri.getLastPathSegment();
                    int index = lastPathSegment.lastIndexOf("/");

                    String name = lastPathSegment.substring(index + 1);
                    String importPath = Common.getImportPath(name);
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            File file = new File(importPath);
                            boolean isimport = MyDb.queryIsImport(importPath);
                            if (file.exists()) {
                                if (!isimport) {
                                    MyDb.insertImport(importPath);
                                }
                                requireActivity().runOnUiThread(() -> {
                                    binding.loading.setVisibility(View.GONE);
                                    if (isimport) {
                                        Toast.makeText(requireContext(), getString(R.string.import_already), Toast.LENGTH_SHORT).show();
                                    } else {
                                        BeanImport beanImport = new BeanImport();
                                        beanImport.setUri(importPath);
                                        adapterGallery.addData(beanImport);
                                        updateUi(true);
                                    }
                                });
                            } else {
                                boolean b = Common.saveToInternalStorage(name, imageUri, requireContext());
                                if (b) {
                                    MyDb.insertImport(importPath);
                                }
                                requireActivity().runOnUiThread(() -> {
                                    binding.loading.setVisibility(View.GONE);
                                    if (b) {
                                        BeanImport beanImport = new BeanImport();
                                        beanImport.setUri(importPath);
                                        adapterGallery.addData(beanImport);
                                        updateUi(true);
                                    } else {
                                        Toast.makeText(requireContext(), getString(R.string.import_fail), Toast.LENGTH_SHORT).show();
                                    }
                                });
                            }

                        }
                    }).start();
                }

            }

        });
    }

    private void checkPermission() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            permissions = new String[]{Manifest.permission.READ_MEDIA_IMAGES};
        } else {
            permissions = new String[]{Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE};
        }
        if (!Common.checkPermission(requireActivity(), permissions)) {
            permissionsLauncher.launch(permissions);
        } else {
            takeGallery();
        }
    }



    private void takeGallery() {
        Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        intent.setType("image/*");
        intentActivityResultLauncher.launch(intent);
    }


    private void loadImport() {
        adapterGallery = new AdapterGallery(requireActivity());
        new Thread(new Runnable() {
            @Override
            public void run() {
                List<BeanImport> importUrises = MyDb.queryAllImport();
                requireActivity().runOnUiThread(() -> {
                    adapterGallery.setData(importUrises);
                    updateUi(importUrises.size() > 0);
                    binding.loading.setVisibility(View.GONE);
                });
            }
        }).start();
        binding.recyclerview.setAdapter(adapterGallery);
        SpacingItemDecoration spacingItemDecoration = new SpacingItemDecoration(5, true);
        binding.recyclerview.setLayoutManager(new GridLayoutManager(requireActivity(), 3));
        binding.recyclerview.addItemDecoration(spacingItemDecoration);

    }


    private void updateUi(boolean isShow) {
        if (isShow) {
            binding.recyclerview.setVisibility(View.VISIBLE);
            binding.layoutNoImport.setVisibility(View.GONE);
        } else {
            binding.recyclerview.setVisibility(View.GONE);
            binding.layoutNoImport.setVisibility(View.VISIBLE);
        }

    }


}