package cc.winboll.studio.powerbell.receivers;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import cc.winboll.studio.libappbase.LogUtils;
import cc.winboll.studio.powerbell.App;
import cc.winboll.studio.powerbell.MainActivity;
import cc.winboll.studio.powerbell.utils.AppConfigUtils;
import cc.winboll.studio.powerbell.utils.BatteryUtils;

public class GlobalApplicationReceiver extends BroadcastReceiver {

    public static final String TAG = "GlobalApplicationReceiver";

    private AppConfigUtils mAppConfigUtils;
    private App mGlobalApplication;
    // 存储历史电池状态，用于判断变化（优化命名，明确语义）
    private static volatile int sLastBatteryLevel = -1; // 历史电量（0-100）
    private static volatile boolean sLastIsCharging = false; // 历史充电状态
    // 当前Receiver实例（优化命名，避免歧义）
    private GlobalApplicationReceiver mCurrentReceiver;

    // 构造方法（强化参数校验，避免空指针）
    public GlobalApplicationReceiver(App globalApplication) {
        if (globalApplication == null) {
            LogUtils.e(TAG, "GlobalApplicationReceiver: App instance is null");
            throw new IllegalArgumentException("App cannot be null");
        }
        this.mCurrentReceiver = this;
        this.mGlobalApplication = globalApplication;
        this.mAppConfigUtils = App.getAppConfigUtils(mGlobalApplication);
    }

    @Override
    public void onReceive(Context context, Intent intent) {
        LogUtils.d(TAG, "onReceive: enter, action=" + intent.getAction());
        // 双重空指针防护（context/intent/action 均校验）
        if (context == null || intent == null || intent.getAction() == null) {
            LogUtils.e(TAG, "onReceive: invalid params (context/intent is null)");
            return;
        }

        // 仅处理电池状态变化广播
        if (Intent.ACTION_BATTERY_CHANGED.equals(intent.getAction())) {
            handleBatteryStateChanged(context, intent);
        }
        LogUtils.d(TAG, "onReceive: exit");
    }

    /**
     * 处理电池状态变化（核心逻辑：复用 BatteryUtils，优化状态同步）
     */
    private void handleBatteryStateChanged(Context context, Intent intent) {
        // 1. 用 BatteryUtils 解析当前电池状态（复用工具类，避免重复代码）
        boolean currentIsCharging = BatteryUtils.isCharging(context); // 调用工具类判断充电状态
        int currentBatteryLevel = BatteryUtils.getCurrentBattery(context); // 调用工具类获取电量（0-100）
        currentBatteryLevel = Math.min(Math.max(currentBatteryLevel, 0), 100); // 二次校验，确保范围有效

        LogUtils.d(TAG, "handleBatteryStateChanged: current - charging=" + currentIsCharging + ", level=" + currentBatteryLevel);

        // 2. 状态无变化，直接跳过（避免无效运算）
        if (currentIsCharging == sLastIsCharging && currentBatteryLevel == sLastBatteryLevel) {
            LogUtils.d(TAG, "handleBatteryStateChanged: no state change, skip");
            return;
        }

        // 3. 同步最新状态到配置工具类（确保配置实时更新）
        if (mAppConfigUtils != null) {
            if (currentIsCharging != sLastIsCharging) {
                mAppConfigUtils.setCharging(currentIsCharging); // 同步充电状态
            }
            if (currentBatteryLevel != sLastBatteryLevel) {
                mAppConfigUtils.setCurrentBatteryValue(currentBatteryLevel); // 同步当前电量
            }
        } else {
            LogUtils.e(TAG, "handleBatteryStateChanged: AppConfigUtils is null, sync failed");
        }

        // 4. 电池状态变化后的业务逻辑（保留原有逻辑，强化空指针防护）
        // 取消旧提醒（若后续需要启用，可调用 NotificationHelper.cancelRemindNotification(context)）
        // 记录电量变化时间
        if (App.getAppCacheUtils(context) != null) {
            App.getAppCacheUtils(context).addChangingTime(currentBatteryLevel);
        }
        // 发送电量更新消息到MainActivity
        MainActivity.sendCurrentBatteryValueMessage(currentBatteryLevel);

        // 5. 更新历史状态缓存（volatile 保证多线程可见性）
        sLastIsCharging = currentIsCharging;
        sLastBatteryLevel = currentBatteryLevel;
        LogUtils.d(TAG, "handleBatteryStateChanged: sync success, update last state");
    }

    // 注册广播（优化容错，避免重复注册）
    public void registerAction() {
        if (mGlobalApplication == null || mCurrentReceiver == null) {
            LogUtils.e(TAG, "registerAction: App/receiver is null, register failed");
            return;
        }

        try {
            // 先注销再注册，避免重复注册导致异常
            unregisterAction();
            IntentFilter filter = new IntentFilter();
            filter.addAction(Intent.ACTION_BATTERY_CHANGED);
            mGlobalApplication.registerReceiver(mCurrentReceiver, filter);
            LogUtils.d(TAG, "registerAction: broadcast receiver registered success");
        } catch (Exception e) {
            LogUtils.e(TAG, "registerAction: register failed", e);
        }
    }

    // 新增：注销广播（避免内存泄漏，供外部调用）
    public void unregisterAction() {
        if (mGlobalApplication == null || mCurrentReceiver == null) {
            LogUtils.e(TAG, "unregisterAction: App/receiver is null, unregister failed");
            return;
        }

        try {
            mGlobalApplication.unregisterReceiver(mCurrentReceiver);
            LogUtils.d(TAG, "unregisterAction: broadcast receiver unregistered success");
        } catch (IllegalArgumentException e) {
            LogUtils.w(TAG, "unregisterAction: receiver not registered, skip");
        } catch (Exception e) {
            LogUtils.e(TAG, "unregisterAction: unregister failed", e);
        }
    }

    // 新增：主动释放资源（供App销毁时调用，彻底防泄漏）
    public void release() {
        LogUtils.d(TAG, "release: receiver release resources");
        unregisterAction();
        mGlobalApplication = null;
        mAppConfigUtils = null;
        mCurrentReceiver = null;
        // 重置静态缓存
        sLastBatteryLevel = -1;
        sLastIsCharging = false;
    }
}

