# *****************************************************************************
# 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:
#   Marcel Fuchs <marcel.fuchs@psi.ch>
# *****************************************************************************


"""
Multiple waterbath switching
"""

from frappy.core import Readable, Writable, Parameter, Property, IntRange, Attached,ERROR, IDLE, WARN

class Switcher(Writable):
    value = Parameter("Switcher state", IntRange(0,3))
    target = Parameter("Switcher target", IntRange(0,3), default=0)
    valve1 = Attached(Writable)
    valve2 = Attached(Writable)
    valve3 = Attached(Writable)
    _count = 0
    _idle_status = IDLE, ''

    def initModule(self):
        super().initModule()
        self.valves = {1:self.valve1, 2:self.valve2, 3:self.valve3}
    
    def write_target(self, target):
        for nr, valve in self.valves.items():
            if nr != target:
                valve.write_target(False)
        if target != 0:
            self.valves[target].write_target(True)
        self._idle_status = IDLE, ''

    def read_value(self):
        opened = [nr for nr, valve in self.valves.items() if valve.read_value()]
        self._count = len(opened)
        if self._count == 0:
            return 0
        if self._count == 1:
            return opened[0]
        self.write_target(self.target)
        self._idle_status = WARN, 'superfluous valves closed'
        return self.target
    
    def read_status(self):
        return self._idle_status
        