# *****************************************************************************
#
# 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 2 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, write to the Free Software Foundation, Inc.,
# 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
#
# Module authors:
#  Anik Stark <anik.stark@psi.ch>
#
# *****************************************************************************

import time
from frappy.core import Parameter, EnumType, FloatRange, Writable


class Valve(Writable):

    value = Parameter('state of valve (open or close)', datatype=EnumType(open=1, close=0))
    target = Parameter('open or close valve', datatype=EnumType(open=1, close=0))

    def write_target(self, target):
        self.value = target


class PulsedValve(Valve):

    delay = Parameter('delay (time valve is open)', FloatRange(unit='s'), readonly=False)
    _start = 0

    def write_target(self, target):
        if target:
            self._start = time.time()
            self.setFastPoll(True, 0.01)
            self.value = target
        else:
            self.setFastPoll(False)

    def doPoll(self):
        super().doPoll()
        if self._start:
            if time.time() > self._start + self.delay:
                self.write_target(0)
                self.value = 0
                self._start = 0


class Sensor(Writable):
    """ Pressure and motor valve. """

    value = Parameter('sensor value', datatype=FloatRange(), readonly=False)

    def write_target(self, target):
        self.value = target
