package com.paint.trace.drawing.frag;

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.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.GridLayoutManager;

import com.paint.trace.drawing.R;
import com.paint.trace.drawing.databinding.FragmentImportBinding;
import com.paint.trace.drawing.db.ObjectBox;
import com.paint.trace.drawing.item.ImportImgAdapter;
import com.paint.trace.drawing.other.ImportData;
import com.paint.trace.drawing.other.Utils;
import com.paint.trace.drawing.topon.AdManager;
import com.paint.trace.drawing.topon.onActionListener;
import com.paint.trace.drawing.view.MyApplication;

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

public class FragmentAlbum extends Fragment {
    private FragmentImportBinding binding;
    private String[] permissions;
    private boolean hasPermission = false;
    private ImportImgAdapter importImgAdapter;
    private ActivityResultLauncher<Intent> intentActivityResultLauncher;
    public FragmentAlbum() {

    }
    public static FragmentAlbum newInstance() {
        FragmentAlbum fragment = new FragmentAlbum();
        return fragment;
    }
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        binding = FragmentImportBinding.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) {
                AdManager.showTopOn(requireActivity(), new onActionListener() {
                    @Override
                    public void onAction() {
                        checkPermission();
                    }
                });
            }
        });

        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 = Utils.getUriFileSize(requireContext(), imageUri);
                    Log.d(MyApplication.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 = Utils.getImportPath(name);
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            File file = new File(importPath);
                            boolean isimport = ObjectBox.queryIsImport(importPath);
                            if(file.exists()){
                                if(!isimport){
                                    ObjectBox.insertImport(importPath);
                                }
                                requireActivity().runOnUiThread(()->{
                                    binding.loading.setVisibility(View.GONE);
                                    if (isimport) {
                                        Toast.makeText(requireContext(), getString(R.string.import_already), Toast.LENGTH_SHORT).show();
                                    } else {
                                        ImportData importData = new ImportData();
                                        importData.setUri(importPath);
                                        importImgAdapter.addData(importData);
                                        updateUi(true);
                                    }
                                });
                            }else {
                                boolean b = Utils.saveToInternalStorage(name, imageUri,    requireActivity());
                                if (b) {
                                    ObjectBox.insertImport(importPath);
                                }
                                requireActivity().runOnUiThread(()->{
                                    binding.loading.setVisibility(View.GONE);
                                    if (b) {
                                        ImportData importData = new ImportData();
                                        importData.setUri(importPath);
                                        importImgAdapter.addData(importData);
                                        updateUi(true);
                                    } else {
                                        Toast.makeText(   requireActivity(), 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 (!Utils.checkPermission(   requireActivity(), permissions)) {
            hasPermission = false;
            ActivityCompat.requestPermissions(   requireActivity(), permissions, 0);
        } else {
            hasPermission = true;
            startIntent();
        }
    }


    private void startIntent() {
        Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        intentActivityResultLauncher.launch(intent);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == 0) {
            if (Utils.checkPermission(requireActivity(), permissions)) {
                hasPermission = true;
                startIntent();
            } else {
                hasPermission = false;
            }

        }
    }

    public void permissionResult(){
        if (Utils.checkPermission(requireActivity(), permissions)) {
            hasPermission = true;
            startIntent();
        } else {
            hasPermission = false;
        }
    }

    private void loadImport() {
        importImgAdapter = new ImportImgAdapter(   requireActivity());
        new Thread(new Runnable() {
            @Override
            public void run() {
                List<ImportData> importUrises = ObjectBox.queryAllImport();
                requireActivity().runOnUiThread(()->{
                    importImgAdapter.setData(importUrises);
                    updateUi(importUrises.size()>0);
                    binding.loading.setVisibility(View.GONE);
                });
            }
        }).start();


        binding.recyclerview.setAdapter(importImgAdapter);
        binding.recyclerview.setLayoutManager(new GridLayoutManager(   requireActivity(), 3));
    }


    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);
        }

    }
}