from hass_client import HomeAssistantClient

from aiplusiot.sensors.standard_sensors.StandardSensor import StandardSensor
from aiplusiot.sensors.standard_sensors.SensorClasses import SensorClass


class BatterySensor(StandardSensor):
    def __init__(self, hass_instance: HomeAssistantClient, sensor_info: dict) -> None:
        """
        | Initializes a Battery sensor using a sensor data dict

        :param hass_instance: Instance of the HomeAssistant Client
        :type hass_instance: HomeAssistantClient

        :param sensor_info: Sensor data dictionary
        :type sensor_info: dict
        """
        super().__init__(hass_instance, sensor_info)
        self.sensor_class = SensorClass.BATTERY
        if  sensor_info['state'] == 'unavailable':
            self.level = -1
            self.battery_voltage = -1

        else:
            self.level = int(sensor_info['state'])
            self.battery_voltage = float(sensor_info['attributes']['battery_voltage'])

    def get_voltage(self) -> float:
        """
        | Gets the current voltage of the sensor


        :return: Current voltage
        :rtype: float
        """

        return self.battery_voltage

    def get_percentage(self) -> int:
        """
        | Gets the current percentage of battery


        :return: Current charge in percentage
        :rtype: int
        """
        return self.level

    async def _update_fields(self, event_details: dict) -> None:
        await super(BatterySensor, self)._update_fields(event_details)

        self.level = event_details['new_state']['state']
        self.battery_voltage = event_details['new_state']['attributes']['battery_voltage']
