package com.swiftcleaner.chovey.view.activity;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.LinearLayoutManager;

import android.Manifest;
import android.animation.ValueAnimator;
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Build;
import android.os.CountDownTimer;
import android.os.Environment;
import android.provider.Settings;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

import com.gyf.immersionbar.ImmersionBar;
import com.swiftcleaner.chovey.R;
import com.swiftcleaner.chovey.business.EventUtils;
import com.swiftcleaner.chovey.business.admob.AdmobManager;
import com.swiftcleaner.chovey.databinding.ActivityAppProcessBinding;
import com.swiftcleaner.chovey.model.bean.AppInfoBean;
import com.swiftcleaner.chovey.model.tool.MemoryUtils;
import com.swiftcleaner.chovey.model.util.FinishMain;
import com.swiftcleaner.chovey.view.BaseActivity;
import com.swiftcleaner.chovey.view.BaseActivityKotlin;
import com.swiftcleaner.chovey.view.MainActivity;
import com.swiftcleaner.chovey.view.adapter.AppProcessAdapter;
import com.swiftcleaner.chovey.view.dialog.CustomScoreDialog;
import com.swiftcleaner.chovey.view.dialog.LoadingDialog;

import java.util.ArrayList;
import java.util.List;

public class AppProcessActivity extends BaseActivity<ActivityAppProcessBinding> {
    private AppProcessAdapter adapter;
    private ValueAnimator animator;
    private CountDownTimer countDownTimer;
    private static final int REQUEST_ALL_FILES_ACCESS_PERMISSION = 100;
    private static final int REQUEST_PERMISSION_CODE = 101;
    @Override
    protected ActivityAppProcessBinding getViewBinding() {
        return ActivityAppProcessBinding.inflate(getLayoutInflater());
    }

    @Override
    protected void initView() {
        initBar();
    }


    @Override
    protected void initData() {
        EventUtils.INSTANCE.event("page_AppProcessActivity", "", null);
        initPage();
        initShow();
    }
    private void initPage() {
        binding.clRadarview.setVisibility(View.VISIBLE);
        binding.radarview.setSearching(true);
        AdmobManager.INSTANCE.showNativeAd(AppProcessActivity.this, (nativeAd) -> {
            binding.flAdDonghua.removeAllViews();
            binding.flAdDonghua.setNativeAd(nativeAd, R.layout.layout_ad_native);
            return null;
        }, null, null);
        initAnimotor();
        countDownTimer = new CountDownTimer(5000, 1000) {
            @Override
            public void onTick(long millisUntilFinished) {
            }

            @Override
            public void onFinish() {
                binding.radarview.setSearching(false);
                countDownTimer.cancel();
                animator.cancel();
                binding.clRadarview.setVisibility(View.GONE);
                LoadingDialog loadingDialog = new LoadingDialog(AppProcessActivity.this);
                loadingDialog.show();
                if (AdmobManager.INSTANCE.isShowAdInter()){
                    AdmobManager.INSTANCE.showInterstitialAd(AppProcessActivity.this, () -> {
                                return null;
                            },
                            () -> {
                                loadingDialog.dismiss();
                                checkAndRequestPermissions();
                                binding.flAdDonghua.removeAllViews();
                                return null;
                            },
                            () -> {
                                loadingDialog.dismiss();
                                checkAndRequestPermissions();
                                binding.flAdDonghua.removeAllViews();
                                return null;
                            }, false);
                }else {
                    checkAndRequestPermissions();
                    loadingDialog.dismiss();
                }
            }
        }.start();
        AdmobManager.INSTANCE.showNativeAd(AppProcessActivity.this, (nativeAd) -> {
            binding.flAd.removeAllViews();
            binding.flAd.setNativeAd(nativeAd, R.layout.layout_ad_native);
            return null;
        }, null, null);
    }
    private void initAnimotor(){
        // 创建ValueAnimator，从1到100
        animator = ValueAnimator.ofInt(1, 100);
        animator.setDuration(5000); // 3秒

        // 设置更新监听器，每帧更新进度文本
        animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                int currentValue = (int) animation.getAnimatedValue();
                binding.parText.setText(currentValue + "%");
            }
        });
        // 开始动画
        animator.start();
    }
    private void initShow() {
        binding.ivReturn.setOnClickListener(v -> {
            initCustDialog();
        });
        binding.appProcessButtonOk.setOnClickListener(v -> {
            initCustDialog();
        });
        binding.appProcessRecy.setLayoutManager(new LinearLayoutManager(this));

        // 将耗时操作放到子线程中执行
        new Thread(() -> {
            List<AppInfoBean> appInfoList = getNonSystemAppInfos();
            runOnUiThread(() -> {
                adapter = new AppProcessAdapter(appInfoList, this);
                binding.appProcessRecy.setAdapter(adapter);
                initProcess();
            });
        }).start();
    }
    private void checkAndRequestPermissions() {
        if (!checkFilesAccessPermission(this)) {
            // 没有权限，请求权限
            requestFilesAccessPermission();
        }
    }

    private boolean checkFilesAccessPermission(Context context) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
            return Environment.isExternalStorageManager();
        } else {
            int readPermission = ContextCompat.checkSelfPermission(context, Manifest.permission.READ_EXTERNAL_STORAGE);
            int writePermission = ContextCompat.checkSelfPermission(context, Manifest.permission.WRITE_EXTERNAL_STORAGE);
            return readPermission == PackageManager.PERMISSION_GRANTED && writePermission == PackageManager.PERMISSION_GRANTED;
        }
    }

    private void requestFilesAccessPermission() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
            try {
                Intent intent = new Intent(Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION);
                intent.addCategory("android.intent.category.DEFAULT");
                intent.setData(Uri.parse("package:" + getPackageName()));
                startActivityForResult(intent, REQUEST_ALL_FILES_ACCESS_PERMISSION);
            } catch (ActivityNotFoundException e) {
                Toast.makeText(this, "Unable to request permission, please grant manually", Toast.LENGTH_SHORT).show();
            }
        } else {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_PERMISSION_CODE);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == REQUEST_ALL_FILES_ACCESS_PERMISSION) {
            if (!checkFilesAccessPermission(this)) {
                // 权限未授予，直接关闭页面
                Toast.makeText(this, "Unauthorized permission, the page is about to close", Toast.LENGTH_SHORT).show();
                finish();
            }
        } else if (requestCode == REQUEST_PERMISSION_CODE) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED && grantResults[1] == PackageManager.PERMISSION_GRANTED) {
                // 权限已授予，可以继续操作
            } else {
                // 权限未授予，直接关闭页面
                Toast.makeText(this, "Unauthorized permission, the page is about to close", Toast.LENGTH_SHORT).show();
                finish();
            }
        }
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_ALL_FILES_ACCESS_PERMISSION) {
            // 检查权限是否已经授予
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
                if (Environment.isExternalStorageManager()) {
                    // 权限已授予，刷新页面或执行相关操作
                    Intent intent = new Intent(this, MainActivity.class);
                    startActivity(intent);
                    finish();
                } else {
                    // 权限未授予，提示用户
                    Toast.makeText(this, "Permission not granted, please grant manually", Toast.LENGTH_SHORT).show();
                }
            }
        }
    }
    private void initProcess() {
        // 获取总内存
        String totalMemory = MemoryUtils.getUsedDiskMemory(this);

        // 获取当前使用内存
        String usedMemory = MemoryUtils.getTotalDiskMemory(this);

        String usedDiskMemoryPercent = MemoryUtils.getUsedDiskMemoryPercent(this);

        binding.memoryInfoText.setText(totalMemory + "/" + usedMemory);
        binding.appProcessNum.setText(usedDiskMemoryPercent);

        try {
            int percent = Integer.parseInt(usedDiskMemoryPercent.replaceAll("%", ""));
            binding.progressBar.setProgress(percent);
        } catch (NumberFormatException e) {
            e.printStackTrace();
            Log.e("AppProcessActivity", "Error parsing used disk memory percent: " + e.getMessage());
            binding.progressBar.setProgress(0);

        }
    }

    private List<AppInfoBean> getNonSystemAppInfos() {
        PackageManager packageManager = getPackageManager();
        List<ApplicationInfo> installedApps = packageManager.getInstalledApplications(0);

        // 过滤掉系统应用
        List<ApplicationInfo> nonSystemApps = new ArrayList<>();
        for (ApplicationInfo appInfo : installedApps) {
            if ((appInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0) {
                nonSystemApps.add(appInfo);
            }
        }

        // 过滤掉当前应用
        List<ApplicationInfo> nonSystemAppsFiltered = new ArrayList<>();
        String currentPackageName = getPackageName();
        for (ApplicationInfo appInfo : nonSystemApps) {
            if (!currentPackageName.equals(appInfo.packageName)) {
                nonSystemAppsFiltered.add(appInfo);
            }
        }

        // 将ApplicationInfo对象转换为AppInfoBean对象
        List<AppInfoBean> apps = new ArrayList<>();
        for (ApplicationInfo packageInfo : nonSystemAppsFiltered) {
            String appName = packageManager.getApplicationLabel(packageInfo).toString();
            Drawable appIcon = packageInfo.loadIcon(packageManager);
            AppInfoBean appInfoBean = new AppInfoBean(appName, appIcon, packageInfo.packageName);
            apps.add(appInfoBean);
        }
        return apps;
    }

    private void initBar() {
        ImmersionBar.with(this)
                .transparentStatusBar()  // 透明状态栏
                .statusBarDarkFont(false)  // 状态栏字体颜色为浅色
                .navigationBarDarkIcon(true)  // 导航栏图标颜色为浅色
                .init();
    }

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

    private void initCustDialog() {
        Activity activity = this;
        CustomScoreDialog customScoreDialog = new CustomScoreDialog(this);
        customScoreDialog.setOnDialogClickListener(new CustomScoreDialog.OnDialogClickListener() {
            @Override
            public void onCancel() {
                customScoreDialog.dismiss();
            }

            @Override
            public void onSubmit() {
                if (AdmobManager.INSTANCE.isShowAdBackInter()){
                    AdmobManager.INSTANCE.showInterstitialAd(AppProcessActivity.this, () -> {
                                FinishMain.INSTANCE.finishToMain(activity);
                                return null;
                            },
                            () -> {
                                return null;
                            },
                            () -> {
                                FinishMain.INSTANCE.finishToMain(activity);
                                if (AdmobManager.INSTANCE.isShowAdInter()){

                                }
                                return null;
                            }, false);
                }else {
                    FinishMain.INSTANCE.finishToMain(activity);
                }
            }
        });
        customScoreDialog.show();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (binding.radarview != null) {
            binding.radarview.setSearching(false);
        }
        if (animator != null) {
            animator.cancel();
        }
        if (countDownTimer!=null){
            countDownTimer.cancel();
        }
    }
}