package com.swiftcleaner.chovey.view.activity;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;

import android.os.Bundle;
import android.view.View;

import com.gyf.immersionbar.ImmersionBar;
import com.swiftcleaner.chovey.databinding.ActivitySimilarPhotosBinding;
import com.swiftcleaner.chovey.model.bean.CleanFileBean;
import com.swiftcleaner.chovey.model.bean.SimilarBean;
import com.swiftcleaner.chovey.model.bean.ImageHelpers;
import com.swiftcleaner.chovey.model.tool.MediaHelps;
import com.swiftcleaner.chovey.view.adapter.SimilarPhotosAdapter;
import com.swiftcleaner.chovey.view.dialog.CustomScoreDialog;
import com.zxdemo.admob.AdmobHelper;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;

public class SimilarPhotosActivity extends AppCompatActivity {
    private ExecutorService executorService = Executors.newSingleThreadExecutor();
    private Semaphore semaphore = new Semaphore(10); // 限制并发数
    ActivitySimilarPhotosBinding binding;
    SimilarPhotosAdapter similarPhotosAdapter;
    private long selectedSize = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivitySimilarPhotosBinding.inflate(getLayoutInflater());
        View view = binding.getRoot();
        setContentView(view);
        initBar();
        initShow();
    }

    private void initShow() {
        binding.ivReturn.setOnClickListener(v -> {
            initCustDialog();
        });

        initSimilar();
    }

    private List<SimilarBean> groupSimilarImages(List<SimilarBean> similarBeans) {
        Set<String> hasSame = new HashSet<>();
        List<SimilarBean> groupedBeans = new ArrayList<>();

        for (SimilarBean similar : similarBeans) {
            if (!hasSame.contains(similar.getUrl())) {
                hasSame.add(similar.getUrl());
                similar.getItems().add(similar);
                for (SimilarBean other : similarBeans) {
                    if (!hasSame.contains(other.getUrl()) && ImageHelpers.similarCondition(similar, other)) {
                        hasSame.add(other.getUrl());
                        similar.getItems().add(other);
                    }
                }
                groupedBeans.add(similar);
            }
        }

        return groupedBeans;
    }

    private void initSimilar() {
        executorService.submit(() -> {
            List<CleanFileBean> images = MediaHelps.findImageFiles(this, 0);
            List<SimilarBean> similarBeans = new ArrayList<>();
            for (CleanFileBean image : images) {
                try {
                    semaphore.acquire();
                    SimilarBean bean = ImageHelpers.createImage(image.getPath());
                    if (bean != null) {
                        similarBeans.add(bean);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    semaphore.release();
                }
            }

            List<SimilarBean> groupedBeans = groupSimilarImages(similarBeans);
            runOnUiThread(() -> {
//                progressBar.setVisibility(android.view.View.GONE);
                similarPhotosAdapter = new SimilarPhotosAdapter(groupedBeans, new SimilarPhotosAdapter.OnItemClickListener() {
                    @Override
                    public void onItemClick(CleanFileBean fileBean) {

                    }
                });
                binding.similarPhotosRecy.setAdapter(similarPhotosAdapter);
                binding.similarPhotosRecy.setLayoutManager(new LinearLayoutManager(this));
            });


//            List<CleanFileBean> imageFiles = MediaHelps.findImageFiles(this, 0);
//
//            // 异步获取相似图片
//            List<SimilarBean> similarBeans = imageFiles.stream()
//                    .map(value -> {
//                        try {
//                            semaphore.acquire();
//                            try {
//                                return ImageHelpers.createImage(value.getPath());
//                            } finally {
//                                semaphore.release();
//                            }
//                        } catch (InterruptedException e) {
//                            e.printStackTrace();
//                            return null;
//                        }
//                    })
//                    .filter(Objects::nonNull)
//                    .collect(Collectors.toList());
//
//            // 处理相似图片逻辑
//            Set<String> hasSame = new HashSet<>();
//            for (SimilarBean similar : similarBeans) {
//                if (hasSame.contains(similar.getUrl())) continue;
//                hasSame.add(similar.getUrl());
//                similar.getItems().add(similar);
//                for (SimilarBean it : similarBeans) {
//                    if (!hasSame.contains(it.getUrl()) && ImageHelpers.similarCondition(similar, it)) {
//                        hasSame.add(it.getUrl());
//                        similar.getItems().add(it);
//                    }
//                }
//            }
//
//            // 过滤出相似图片集合
//            List<SimilarBean> list = similarBeans.stream()
//                    .filter(bean -> bean.getItems().size() > 1)
//                    .collect(Collectors.toList());
//
//            runOnUiThread(() -> {
//
//                similarPhotosAdapter = new SimilarPhotosAdapter(list, new SimilarPhotosAdapter.OnItemClickListener() {
//                    @Override
//                    public void onItemClick(CleanFileBean fileBean) {
//                        if (fileBean.isSelected()) {
//                            selectedSize += fileBean.getLength();
//                            updateButtonStatus();
//                        } else {
//                            selectedSize -= fileBean.getLength();
//                            updateButtonStatus();
//                        }
//                    }
//                });
//                binding.similarPhotosRecy.setAdapter(similarPhotosAdapter);
//                binding.similarPhotosRecy.setLayoutManager(new LinearLayoutManager(this));
//            });
//
//            // 关闭线程池
//            executorService.shutdown();
//            try {
//                executorService.awaitTermination(1, TimeUnit.MINUTES);
//            } catch (InterruptedException e) {
//                e.printStackTrace();
//            }
        });
    }

    private void updateButtonStatus() {
//        binding.buttonCleanUp.setText("Clean Up " + formatFileSize(selectedSize));
////        if (selectedSize == 0) {
////            binding.buttonCleanUp.setBackground(ContextCompat.getDrawable(this, R.drawable.shape_radio_80dp_hui_se));
////        } else {
////            binding.buttonCleanUp.setBackground(ContextCompat.getDrawable(this, R.drawable.shape_clean_up));
////        }
    }

    private void initBar() {
        ImmersionBar.with(this)
                .transparentStatusBar()  // 透明状态栏
                .statusBarDarkFont(false)  // 状态栏字体颜色为浅色
                .navigationBarDarkIcon(true)  // 导航栏图标颜色为浅色
                .init();
    }
    private void initCustDialog() {
        CustomScoreDialog customScoreDialog = new CustomScoreDialog(this);
        customScoreDialog.setOnDialogClickListener(new CustomScoreDialog.OnDialogClickListener() {
            @Override
            public void onCancel() {
                customScoreDialog.dismiss();
            }

            @Override
            public void onSubmit() {
                AdmobHelper.INSTANCE.showInterstitialAd(SimilarPhotosActivity.this, () -> {
                            finish();
                            return null;
                        },
                        () -> {
                            return null;
                        },
                        () -> {
                            finish();
                            return null;
                        });
            }
        });
        customScoreDialog.show();
    }

    @Override
    public void onBackPressed() {
        initCustDialog();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        executorService.shutdown();
    }
}