# /*
#  * Copyright (C) 2020, KylinSoft Co., Ltd.
#  *
#  * This program is free software: you can redistribute it and/or modify
#  * it under the terms of the GNU General Public License as published by
#  * the Free Software Foundation, either version 3 of the License, or
#  * (at your option) any later version.
#  *
#  * This program is distributed in the hope that it will be useful,
#  * but WITHOUT ANY WARRANTY; without even the implied warranty of
#  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#  * GNU General Public License for more details.
#  *
#  * You should have received a copy of the GNU General Public License
#  * along with this program.  If not, see <https://www.gnu.org/licenses/>.
#  */

import dbus
import logging
from gettext import gettext as _
from SystemUpdater.Core.errors import *
from SystemUpdater.Core.enums import *
from SystemUpdater.checks.registry import register_check

POWER_REQUIRES = 20  # 设备最低电量要求百分比

@register_check("check-device-power", roles=[ROLE_DEPLOY])
def check_device_power(trans):
    logging.info("Check: Device power...")
    check_power(trans)

def check_power(trans):
    power_percentage = 0
    requires = 0
    try:
        bus = dbus.SystemBus()
        obj = bus.get_object("org.freedesktop.UPower","/org/freedesktop/UPower/devices/DisplayDevice")
        interface = dbus.Interface(obj, "org.freedesktop.DBus.Properties")

        # 获取供电方式
        power_type = int(interface.Get("org.freedesktop.UPower.Device","State",timeout=0.5))
        
        logging.info("Check: Currently powered state:%d",power_type)
        # 非电池方式直接退出检查
        # 1. 台式机为0   2. 插上电源充电 1   3. 未插入电源，用电池2 4. 插上电源充电，充满4 
        # if power_type == 0 or power_type == 1 or power_type == 4:
        if power_type == 2:
            # 电池供电方式
            power_percentage = int(interface.Get("org.freedesktop.UPower.Device","Percentage",timeout=0.5))
            requires = POWER_REQUIRES
            logging.info("Check: Now device power is percentage:%d and requires:%d...",power_percentage,requires)

    except Exception as e:
        logging.error(str(e))

    if power_percentage != 0 and power_percentage < requires:
        logging.error("Not enough device power to shutdown install")
        raise UpdateBaseError(ERROR_DEVICE_LOW_BATTERY)
    return 