"""
measurement_handler.py
"""

from handler_library.handler import PayloadHandler
from PySide2.QtCore import Signal
import logging


class MeasurementHandler(PayloadHandler):
    """
    Subclass of the PayloadHandler class (handler.py) to handle cycle and readback data.
    """

    UpdateMeasurements = Signal(dict)

    def __init__(self, NativeUI=None, *args, name="Measurement handler", **kwargs):
        super().__init__(["CYCLE", "READBACK"], *args, name=name, **kwargs)
        self.NativeUI = NativeUI

    def on_timeout(self) -> int:
        cycle_data = self.get_db()
        outdict = {}

        for key in [
            "plateau_pressure",
            "respiratory_rate",
            "fiO2_percent",
            "exhaled_tidal_volume",
            "exhaled_minute_volume",
            "peak_inspiratory_pressure",
            "mean_airway_pressure",
            "inhaled_tidal_volume",
            "inhaled_minute_volume",
            "peep",
            "inhale_exhale_ratio",
        ]:
            try:
                outdict[key] = cycle_data[key]
            except KeyError:
                logging.debug("Invalid key %s in measurement database", key)

        if self.NativeUI is None:
            logging.warning("MeasurementHandler initialised with nonetype NativeUI - ignore this warning if unit testing")
        else:
            try:
                self.NativeUI.currentMode = cycle_data["ventilation_mode"]
            except KeyError:
                logging.debug("Invalid key %s in measurement database", key)
        if "inhale_exhale_ratio" in outdict:
            outdict["ie_string"] = self.convert_ie_ratio(outdict["inhale_exhale_ratio"])
        else:
            outdict["ie_string"] = "-:-"
        self.UpdateMeasurements.emit(outdict)
        return 0

    def convert_ie_ratio(self, value: float) -> str:
        """
        Convert a floating point value into a string displaying the value as a ratio. 
        The lower of the two numbers should always be 1, the higher should always be a 
        floating point value to 2 decimal places. 
        """
        i:str = "1"
        e:str = "1"
        if value <= 0:
            logging.error("I:E ratio of <= 0")
            return "--"
        elif value < 1:
            i = "1"
            e = "{:.2f}".format(1.0/value)
        elif value > 1:
            i = "{:.2f}".format(value)
            e = "1"
        return i.rstrip("0").rstrip(".") + ":" + e.rstrip("0").rstrip(".")
