package com.swiftcleaner.chovey.view.activity;

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

import android.app.ActivityManager;
import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Debug;
import android.util.Log;
import android.view.View;

import com.gyf.immersionbar.ImmersionBar;
import com.swiftcleaner.chovey.R;
import com.swiftcleaner.chovey.databinding.ActivityAppProcessBinding;
import com.swiftcleaner.chovey.databinding.ActivityEndCleanJunkBinding;
import com.swiftcleaner.chovey.model.bean.AppInfo;
import com.swiftcleaner.chovey.model.bean.AppInfoBean;
import com.swiftcleaner.chovey.model.tool.AppUtils;
import com.swiftcleaner.chovey.model.tool.MemoryUtils;
import com.swiftcleaner.chovey.view.adapter.AppInfoAdapter;
import com.swiftcleaner.chovey.view.adapter.AppProcessAdapter;
import com.swiftcleaner.chovey.view.dialog.CustomScoreDialog;
import com.zxdemo.admob.AdmobHelper;
import com.zxdemo.admob.ReportAdUtils;
import com.zxdemo.http.ZxHttp;

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

public class AppProcessActivity extends AppCompatActivity {
    ActivityAppProcessBinding binding;
    private AppProcessAdapter adapter;

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

    private void initShow() {
        binding.ivReturn.setOnClickListener(v -> {
            initCustDialog();
        });
        binding.appProcessButtonOk.setOnClickListener(v -> {
            initCustDialog();
        });
        binding.appProcessRecy.setLayoutManager(new LinearLayoutManager(this));
        List<AppInfoBean> appInfoList = getNonSystemAppInfos();
        adapter = new AppProcessAdapter(appInfoList, this);
        binding.appProcessRecy.setAdapter(adapter);
        initProcess();
    }

    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() {
        CustomScoreDialog customScoreDialog = new CustomScoreDialog(this);
        customScoreDialog.setOnDialogClickListener(new CustomScoreDialog.OnDialogClickListener() {
            @Override
            public void onCancel() {
                customScoreDialog.dismiss();
            }

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