package cc.winboll.studio.powerbell;

import android.content.Context;
import android.os.Environment;
import android.os.Handler;
import android.os.Looper;
import cc.winboll.studio.libaes.utils.WinBoLLActivityManager;
import cc.winboll.studio.libappbase.GlobalApplication;
import cc.winboll.studio.libappbase.LogUtils;
import cc.winboll.studio.libappbase.ToastUtils;
import cc.winboll.studio.powerbell.models.BackgroundBean;
import cc.winboll.studio.powerbell.receivers.GlobalApplicationReceiver;
import cc.winboll.studio.powerbell.utils.AppCacheUtils;
import cc.winboll.studio.powerbell.utils.AppConfigUtils;
import cc.winboll.studio.powerbell.utils.BackgroundSourceUtils;
import cc.winboll.studio.powerbell.utils.BitmapCacheUtils;
import java.io.File;

public class App extends GlobalApplication {
    public static final String TAG = "App";

    public static final String COMPONENT_EN1 = "cc.winboll.studio.powerbell.MainActivityEN1";
    public static final String COMPONENT_CN1 = "cc.winboll.studio.powerbell.MainActivityCN1";
    public static final String COMPONENT_CN2 = "cc.winboll.studio.powerbell.MainActivityCN2";
    public static final String ACTION_SWITCHTO_EN1 = "cc.winboll.studio.powerbell.App.ACTION_SWITCHTO_EN1";
    public static final String ACTION_SWITCHTO_CN1 = "cc.winboll.studio.powerbell.App.ACTION_SWITCHTO_CN1";
    public static final String ACTION_SWITCHTO_CN2 = "cc.winboll.studio.powerbell.App.ACTION_SWITCHTO_CN2";

    // 数据配置存储工具
    static AppConfigUtils _mAppConfigUtils;
    static AppCacheUtils _mAppCacheUtils;
    // 新增：全局 Bitmap 缓存工具（常驻内存）
    public static BitmapCacheUtils _mBitmapCacheUtils; 

    GlobalApplicationReceiver mReceiver;
    static String szTempDir = "";

    public static String getTempDirPath() {
        return szTempDir;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        setIsDebugging(BuildConfig.DEBUG);

        // 初始化活动窗口管理
        WinBoLLActivityManager.init(this);
        // 初始化 Toast 框架
        ToastUtils.init(this);

        // 临时文件夹初始化（保持原有逻辑）
        File picturesDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
        File powerBellDir = new File(picturesDir, "PowerBell");
        if (!powerBellDir.exists()) {
            powerBellDir.mkdirs();
        }
        szTempDir = powerBellDir.getAbsolutePath();

        // 设置数据配置存储工具
        _mAppConfigUtils = getAppConfigUtils(this);
        _mAppCacheUtils = getAppCacheUtils(this);
        // 初始化全局 Bitmap 缓存工具（关键：App 启动时初始化，常驻内存）
        _mBitmapCacheUtils = BitmapCacheUtils.getInstance();

        mReceiver = new GlobalApplicationReceiver(this);
        mReceiver.registerAction();

        // ======================== 新增：异步预加载背景图 ========================
        new Handler(Looper.getMainLooper()).postDelayed(new Runnable() {
				@Override
				public void run() {
					new Thread(new Runnable() {
							@Override
							public void run() {
								try {
									// 1. 获取背景源工具类实例
									BackgroundSourceUtils bgSourceUtils = BackgroundSourceUtils.getInstance(App.this);
									if (bgSourceUtils == null) {
										LogUtils.e(TAG, "preloadBitmap: BackgroundSourceUtils 实例为空");
										return;
									}
									// 2. 获取当前背景Bean
									BackgroundBean bgBean = bgSourceUtils.getCurrentBackgroundBean();
									if (bgBean == null || !bgBean.isUseBackgroundFile()) {
										LogUtils.d(TAG, "preloadBitmap: 无有效背景文件，跳过预加载");
										return;
									}
									// 3. 获取背景图路径（优先取压缩图路径）
									String bgPath = bgBean.isUseBackgroundScaledCompressFile()
										? bgBean.getBackgroundScaledCompressFilePath()
										: bgBean.getBackgroundFilePath();
									// 4. 预加载到全局缓存
									if (_mBitmapCacheUtils != null) {
										_mBitmapCacheUtils.cacheBitmap(bgPath);
										LogUtils.d(TAG, "preloadBitmap: 应用启动时预加载成功 - " + bgPath);
									} else {
										LogUtils.e(TAG, "preloadBitmap: 全局 BitmapCacheUtils 未初始化");
									}
								} catch (Exception e) {
									LogUtils.e(TAG, "preloadBitmap: 预加载失败 - " + e.getMessage());
								}
							}
						}).start();
				}
			}, 1000); // 延迟1秒执行，避免阻塞应用初始化
        // ======================== 预加载逻辑结束 ========================
    }

    // 保持原有方法不变
    public static AppConfigUtils getAppConfigUtils(Context context) {
        if (_mAppConfigUtils == null) {
            _mAppConfigUtils = AppConfigUtils.getInstance(context);
        }
        return _mAppConfigUtils;
    }

    public static AppCacheUtils getAppCacheUtils(Context context) {
        if (_mAppCacheUtils == null) {
            _mAppCacheUtils = AppCacheUtils.getInstance(context);
        }
        return _mAppCacheUtils;
    }

    public void clearBatteryHistory() {
        _mAppCacheUtils.clearBatteryHistory();
    }

    @Override
    public void onTerminate() {
        super.onTerminate();
        ToastUtils.release();
        // 可选：App 终止时清空 Bitmap 缓存，释放内存
        if (_mBitmapCacheUtils != null) {
            _mBitmapCacheUtils.clearAllCache();
        }
    }
}

