package com.swiftcleaner.chovey.view.activity;

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

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

import com.gyf.immersionbar.ImmersionBar;
import com.swiftcleaner.chovey.databinding.ActivityWhatsAppBinding;
import com.swiftcleaner.chovey.model.bean.CleanFileBean;
import com.swiftcleaner.chovey.model.tool.FileHelps;
import com.swiftcleaner.chovey.model.tool.FileTypes;
import com.swiftcleaner.chovey.view.adapter.WhatsAppCleanAdapter;
import com.swiftcleaner.chovey.view.dialog.CustomScoreDialog;
import com.zxdemo.admob.AdmobHelper;
import com.zxdemo.http.ZxHttp;
import java.text.DecimalFormat;
import java.util.List;
import java.util.Locale;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.stream.Collectors;

public class WhatsAppActivity extends AppCompatActivity {
    ActivityWhatsAppBinding binding;
//    List<CleanFileBean> cleanFileList;
    WhatsAppCleanAdapter whatsAppCleanAdapter;
    public long totalSelectedSize = 0;
    private long selectedSize = 0;
    List<CleanFileBean> videoList;
    List<CleanFileBean> imageList;
    List<CleanFileBean> audioList;
    private ExecutorService executorService = Executors.newSingleThreadExecutor();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivityWhatsAppBinding.inflate(getLayoutInflater());
        View view = binding.getRoot();
        setContentView(view);
        ZxHttp.INSTANCE.getHttpReportInterface("page_StartActivity", "", null);
        initBar();
        initShow();

    }

    private void initShow() {
        binding.ivReturn.setOnClickListener(v->{
            initCustDialog();
        });
        executorService.submit(() -> {
            List<CleanFileBean> files = FileHelps.findWhatsappFiles();
            Log.d("ssad",files.toString());
            if (files!=null){
                videoList = files.stream()
                        .filter(file -> FileTypes.videos.stream().anyMatch(suffix -> file.getName().toLowerCase(Locale.ROOT).endsWith(suffix)))
                        .collect(Collectors.toList());

                imageList = files.stream()
                        .filter(file -> FileTypes.images.stream().anyMatch(suffix -> file.getName().toLowerCase(Locale.ROOT).endsWith(suffix)))
                        .collect(Collectors.toList());

                audioList = files.stream()
                        .filter(file -> FileTypes.audios.stream().anyMatch(suffix -> file.getName().toLowerCase(Locale.ROOT).endsWith(suffix)))
                        .collect(Collectors.toList());
            }

//            if (videoList != null) {
//                for (CleanFileBean file : videoList) {
//                    if (file.getMineType() != null && file.getName() != null) {
//                        file.setSelected(true); // 设置为选中状态
//                        cleanFileList.add(file);
//                        totalSelectedSize += file.getLength();
//                        selectedSize += file.getLength(); // 更新 selectedSize
//                    }
//                }
//            }
//            if (imageList != null) {
//                for (CleanFileBean file : imageList) {
//                    if (file.getMineType() != null && file.getName() != null) {
//                        file.setSelected(true); // 设置为选中状态
//                        cleanFileList.add(file);
//                        totalSelectedSize += file.getLength();
//                        selectedSize += file.getLength(); // 更新 selectedSize
//                    }
//                }
//            }
//            if (audioList != null) {
//                for (CleanFileBean file : audioList) {
//                    if (file.getMineType() != null && file.getName() != null) {
//                        file.setSelected(true); // 设置为选中状态
//                        cleanFileList.add(file);
//                        totalSelectedSize += file.getLength();
//                        selectedSize += file.getLength(); // 更新 selectedSize
//                    }
//                }
//            }


            runOnUiThread(() -> {
                whatsAppCleanAdapter = new WhatsAppCleanAdapter(imageList, new WhatsAppCleanAdapter.OnItemClickListener() {
                    @Override
                    public void onItemClick(CleanFileBean fileBean) {
                        if (fileBean.isSelected()) {
                            selectedSize += fileBean.getLength();
                            updateButtonStatus();
                        } else {
                            selectedSize -= fileBean.getLength();
                            updateButtonStatus();
                        }
                    }
                });
                binding.imageFilesRecy.setAdapter(whatsAppCleanAdapter);
                binding.imageFilesRecy.setLayoutManager(new LinearLayoutManager(this));
                binding.wasteNumber.setText(formatFileSize(totalSelectedSize));
            });
        });

    }
    private void updateButtonStatus() {
        binding.buttonCleanUp.setText("Clean Up " + formatFileSize(selectedSize));
    }
    private String formatFileSize(long size) {
        if (size <= 0) return "0 Bytes";
        final String[] units = new String[]{"Bytes", "KB", "MB", "GB", "TB"};
        int digitGroups = (int) (Math.log10(size) / Math.log10(1024));
        return new DecimalFormat("#,##0.#").format(size / Math.pow(1024, digitGroups)) + " " + units[digitGroups];
    }

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

    private void initBar() {
        ImmersionBar.with(this)
                .transparentStatusBar()  // 透明状态栏
                .statusBarDarkFont(true)  // 状态栏字体颜色为深色
                .navigationBarDarkIcon(false)  // 导航栏图标颜色为浅色
                .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(WhatsAppActivity.this, () -> {
                            finish();
                            return null;
                        },
                        () -> {
                            return null;
                        },
                        () -> {
                            finish();
                            return null;
                        });
            }
        });
        customScoreDialog.show();
    }

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