package cc.winboll.studio.powerbell.utils;

import android.app.Notification;
import android.app.NotificationManager;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.BatteryManager;
import cc.winboll.studio.libappbase.LogUtils;
import cc.winboll.studio.powerbell.R;

/**
 * 电池工具类：获取电池状态、发送提醒通知（复用逻辑，避免代码冗余）
 */
public class BatteryUtils {
    private static final String TAG = "BatteryUtils";
    private static final int REMIND_NOTIFICATION_ID = 10087; // 提醒通知ID

    /**
     * 获取当前电池电量（0-100）
     */
    public static int getCurrentBattery(Context context) {
        Intent batteryIntent = context.getApplicationContext().registerReceiver(
			null, new IntentFilter(Intent.ACTION_BATTERY_CHANGED)
        );
        if (batteryIntent == null) return 0;
        // 提取电量（当前电量/总电量 * 100）
        int level = batteryIntent.getIntExtra(BatteryManager.EXTRA_LEVEL, 0);
        int scale = batteryIntent.getIntExtra(BatteryManager.EXTRA_SCALE, 100);
        return (level * 100) / scale;
    }

    /**
     * 判断是否正在充电（有线/无线均可）
     */
    public static boolean isCharging(Context context) {
        Intent batteryIntent = context.getApplicationContext().registerReceiver(
			null, new IntentFilter(Intent.ACTION_BATTERY_CHANGED)
        );
        if (batteryIntent == null) return false;
        int status = batteryIntent.getIntExtra(BatteryManager.EXTRA_STATUS, BatteryManager.BATTERY_STATUS_UNKNOWN);
        return status == BatteryManager.BATTERY_STATUS_CHARGING 
			|| status == BatteryManager.BATTERY_STATUS_FULL;
    }

    /**
     * 显示充电提醒通知
     */
    public static void showChargeReminderNotification(Context context) {
        Notification notification = new Notification.Builder(context)
			.setSmallIcon(R.drawable.ic_launcher)
			.setContentTitle("充电提醒")
			.setContentText("电池电量已达标，建议及时断电保护电池～")
			.setAutoCancel(true) // 点击后取消通知
			.build();
        NotificationManager manager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
        if (manager != null) {
            manager.notify(REMIND_NOTIFICATION_ID, notification);
        }
        LogUtils.d(TAG, "showChargeReminderNotification: notification show");
    }

    /**
     * 显示耗电提醒通知
     */
    public static void showUsageReminderNotification(Context context) {
        Notification notification = new Notification.Builder(context)
			.setSmallIcon(R.drawable.ic_launcher)
			.setContentTitle("耗电提醒")
			.setContentText("电池电量偏低，建议及时充电～")
			.setAutoCancel(true)
			.build();
        NotificationManager manager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
        if (manager != null) {
            manager.notify(REMIND_NOTIFICATION_ID, notification);
        }
        LogUtils.d(TAG, "showUsageReminderNotification: notification show");
    }
}

