"""
pulsewave
=========
Generates a pulse-wave with programmable characteristics.
The transition argument is either a percentage (default to 50%) or an ISO8601 duration.

Arguments::

    {
        "interval" : the period of the cycle e.g. "PT10M"
        "transition" : (optional) the delay to the mid transition, as a percentage or interval "PT10M"
        "delay" : (optional) a time delay by which to shift the waveform
        "invert" : (optional) inverts the output
        "phase_absolute" : (optional) if true then phase is relative to Jan 1970 (so all similar functions will be aligned), otherwise to when timefunction is created
    }
"""


from .timefunction import Timefunction
import isodate
import math

class Pulsewave(Timefunction):
    def __init__(self, engine, device, params):
        """<interval> is the length of a full cycle ____----
           <transition> is when the low-to-high transition happens - either a percentage e.g. "75%" or another ISO interval
           <delay> is the absolute amount that the start is delayed
           If <phase_absolute> then phase of period is relative to 00:00:00 1 Jan 1970, otherwise to when this device is created"""
        self.engine = engine
        self.interval = float(isodate.parse_duration(params["interval"]).total_seconds())
        if "transition" not in params:
            self.transition = 0.5 # Square wave by default
        else:
            if params["transition"].endswith("%"):
                self.transition = float(params["transition"][0:-1]) / 100.0
            else: