# *****************************************************************************
# 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:
#   Markus Zolliker <markus.zolliker@psi.ch>
# *****************************************************************************
"""virtual sensor switching between two others depending on range"""

from frappy.core import ERROR, Attached, BoolType, Parameter, Readable, TupleOf, EnumType, FloatRange


class Sensor(Readable):
    upper = Attached()
    lower = Attached()

    switch_range = Parameter('switching range', datatype=TupleOf(FloatRange(), FloatRange()), readonly=False, default=(0, 0))
    used_sensor = Parameter('sensor to use', EnumType(lower=0, upper=1), readonly=False, default=0)
    value = Parameter(datatype=FloatRange(unit='K'))
    pollinterval = Parameter(export=False)
    status = Parameter(default=(Readable.Status.ERROR, 'unintialized'))

    def initModule(self):
        super().initModule()
        self.rawsensor.registerCallbacks(self)

    def update_value(self, value):
        src = self.upper if self.used_sensor == 'upper' else self.lower
        try:
            self.value = src.value
            self.status = src.status
        except Exception as e:
            self.status = ERROR, repr(e)

    def update_status(self, value):
        self.update_value(None)

    def read_value(self):
        src = self.upper if self.used_sensor == 'upper' else self.lower
        return src.read_value()

    def read_status(self):
        src = self.upper if self.used_sensor == 'upper' else self.lower
        return src.read_status()
