package com.ar.drawing.activity;

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

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 com.ar.drawing.MyDraw;
import com.ar.drawing.R;
import com.ar.drawing.adapter.ImportAdapter;
import com.ar.drawing.databinding.ActivityImportBinding;
import com.ar.drawing.ob.BeanImport;
import com.ar.drawing.ob.DbManager;
import com.ar.drawing.others.Utils;

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

public class ImportActivity extends AppCompatActivity {
    private ActivityImportBinding binding;


    private String[] permissions;

    private ImportAdapter importAdapter;
    private ActivityResultLauncher<Intent> intentActivityResultLauncher;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Utils.setStatusBarTextColor(this,true);
        binding = ActivityImportBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        onInit();
    }


    private void onInit() {
        binding.back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        binding.loading.setVisibility(View.VISIBLE);
        loadImport();
        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(this, imageUri);
                    Log.d(MyDraw.TAG, "------uriFileSize-----" + uriFileSize+"--Mb");
                    if(uriFileSize>=5){
                        binding.loading.setVisibility(View.GONE);
                        Toast.makeText(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 = DbManager.queryIsImport(importPath);
                            if(file.exists()){
                                if(!isimport){
                                    DbManager.insertImport(importPath);
                                }
                                runOnUiThread(()->{
                                    binding.loading.setVisibility(View.GONE);
                                    if (isimport) {
                                        Toast.makeText(ImportActivity.this, getString(R.string.import_already), Toast.LENGTH_SHORT).show();
                                    } else {
                                        BeanImport beanImport = new BeanImport();
                                        beanImport.setUri(importPath);
                                        importAdapter.addData(beanImport);
                                        updateUi(true);
                                    }
                                });
                            }else {
                                boolean b = Utils.saveToInternalStorage(name, imageUri, ImportActivity.this);
                                if (b) {
                                    DbManager.insertImport(importPath);
                                }
                                 runOnUiThread(()->{
                                    binding.loading.setVisibility(View.GONE);
                                    if (b) {
                                        BeanImport beanImport = new BeanImport();
                                        beanImport.setUri(importPath);
                                        importAdapter.addData(beanImport);
                                        updateUi(true);
                                    } else {
                                        Toast.makeText(ImportActivity.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(ImportActivity.this, permissions)) {

            ActivityCompat.requestPermissions(ImportActivity.this, permissions, 0);
        } else {

            startIntent();
        }
    }


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


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


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

    }
}