package com.trace.ar.drawing.activity;

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.View;
import android.widget.Toast;

import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.recyclerview.widget.GridLayoutManager;

import com.trace.ar.drawing.ARApp;
import com.trace.ar.drawing.R;
import com.trace.ar.drawing.adapter.ImportAdapter;
import com.trace.ar.drawing.databinding.ActivityGalleryBinding;
import com.trace.ar.drawing.helper.ImportUri;
import com.trace.ar.drawing.helper.ObjectBox;
import com.trace.ar.drawing.helper.Utils;
import com.trace.ar.drawing.listener.OnDeleteLikeListener;

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

public class GalleryActivity extends AppCompatActivity {

    private ActivityGalleryBinding binding;
    private String[] permissions;
    private boolean hasPermission = false;
    private ImportAdapter importAdapter;
    private ActivityResultLauncher<Intent> intentActivityResultLauncher;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivityGalleryBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        binding.loading.setVisibility(View.VISIBLE);
        Utils.setStatusBarTextColor(this, true);
        loadImport();
        binding.back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        binding.btnImport.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                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(GalleryActivity.this, imageUri);
                    Log.d(ARApp.TAG, "------uriFileSize-----" + uriFileSize+"--Mb");
                    if(uriFileSize>=5){
                        binding.loading.setVisibility(View.GONE);
                        Toast.makeText(GalleryActivity.this, 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);
                                }
                                runOnUiThread(()->{
                                    binding.loading.setVisibility(View.GONE);
                                    if (isimport) {
                                        Toast.makeText(GalleryActivity.this, getString(R.string.import_already), Toast.LENGTH_SHORT).show();
                                    } else {
                                        ImportUri importUri = new ImportUri();
                                        importUri.setUri(importPath);
                                        importAdapter.addData(importUri);
                                        updateUi(true);
                                    }
                                });
                            }else {
                                boolean b = Utils.saveToInternalStorage(name, imageUri, GalleryActivity.this);
                                if (b) {
                                    ObjectBox.insertImport(importPath);
                                }
                                runOnUiThread(()->{
                                    binding.loading.setVisibility(View.GONE);
                                    if (b) {
                                        ImportUri importUri = new ImportUri();
                                        importUri.setUri(importPath);
                                        importAdapter.addData(importUri);
                                        updateUi(true);
                                    } else {
                                        Toast.makeText(GalleryActivity.this, 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(GalleryActivity.this, permissions)) {
            hasPermission = false;
            ActivityCompat.requestPermissions(this, 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(GalleryActivity.this, permissions)) {
                hasPermission = true;
                startIntent();
            } else {
                hasPermission = false;
            }

        }
    }

    private void loadImport() {
        importAdapter = new ImportAdapter(this);
        new Thread(new Runnable() {
            @Override
            public void run() {
                List<ImportUri> importUris = ObjectBox.queryAllImport();
                runOnUiThread(()->{
                    importAdapter.setData(importUris);
                    updateUi(importUris.size()>0);
                    binding.loading.setVisibility(View.GONE);
                });
            }
        }).start();


        importAdapter.setListener(new OnDeleteLikeListener() {
            @Override
            public void onDeleteItem(int pos, String path) {

            }
        });
        binding.recyclerview.setAdapter(importAdapter);
        binding.recyclerview.setLayoutManager(new GridLayoutManager(this, 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);
        }

    }
}