package com.ar.drawing.ui;

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.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.recyclerview.widget.GridLayoutManager;

import com.ar.drawing.MyDraw;
import com.ar.drawing.R;
import com.ar.drawing.ad.AdManager;
import com.ar.drawing.adapter.LocalAdapter;
import com.ar.drawing.databinding.ActivityLocalBinding;
import com.ar.drawing.db.BeanImport;
import com.ar.drawing.db.MyDb;
import com.ar.drawing.others.MyUtils;

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

public class LocalActivity extends AppCompatActivity {
    private ActivityLocalBinding binding;


    private String[] permissions;

    private LocalAdapter localAdapter;
    private ActivityResultLauncher<Intent> intentActivityResultLauncher;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        MyUtils.setStatusBarTextColor(this,true);
        binding = ActivityLocalBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        AdManager.loadAllAd();
        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 = MyUtils.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 = MyUtils.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);
                                }
                                runOnUiThread(()->{
                                    binding.loading.setVisibility(View.GONE);
                                    if (isimport) {
                                        Toast.makeText(LocalActivity.this, getString(R.string.import_already), Toast.LENGTH_SHORT).show();
                                    } else {
                                        BeanImport beanImport = new BeanImport();
                                        beanImport.setUri(importPath);
                                        localAdapter.addData(beanImport);
                                        updateUi(true);
                                    }
                                });
                            }else {
                                boolean b = MyUtils.saveToInternalStorage(name, imageUri, LocalActivity.this);
                                if (b) {
                                    MyDb.insertImport(importPath);
                                }
                                 runOnUiThread(()->{
                                    binding.loading.setVisibility(View.GONE);
                                    if (b) {
                                        BeanImport beanImport = new BeanImport();
                                        beanImport.setUri(importPath);
                                        localAdapter.addData(beanImport);
                                        updateUi(true);
                                    } else {
                                        Toast.makeText(LocalActivity.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 (!MyUtils.checkPermission(LocalActivity.this, permissions)) {

            ActivityCompat.requestPermissions(LocalActivity.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() {
        localAdapter = new LocalAdapter(LocalActivity.this);
        new Thread(new Runnable() {
            @Override
            public void run() {
                List<BeanImport> importUrises = MyDb.queryAllImport();
                runOnUiThread(()->{
                    localAdapter.setData(importUrises);
                    updateUi(importUrises.size()>0);
                    binding.loading.setVisibility(View.GONE);
                });
            }
        }).start();


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

    }
}