# *****************************************************************************
# 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>
# *****************************************************************************
"""iono pi max relais drums

for demo purposes
"""

from frappy.core import Module, Attached, FloatRange, StringType, Writable, Parameter


class Drums(Writable):
    target = Parameter('drum speed', FloatRange(unit='beats/min'))
    left = Attached(Writable)
    right = Attached(Writable)
    pollinterval = Parameter('drum interval', FloatRange(0, 10, unit='s'), readonly=False)
    pattern = Parameter('''pattern

                        a string containing:
                        L,R: left / right relais on
                        l,r: left / right relais off
                        blank: wait''', StringType(), readonly=False)
    _pos = 0
    _wait = 0

    def initModule(self):
        super().initModule()
        self.actions = {'L': self.left, 'R': self.right}

    def write_target(self, target):
        self.pollinterval = 60 / max(1, target)
        self.value = target

    def doPoll(self):
        if not self.target:
            return
        if self._wait:
            self._wait -= 1
            return
        if self._pos >= len(self.pattern):
            self._pos = 0
        for i, action in enumerate(self.pattern[self._pos:]):
            upper = action.upper()
            relais = self.actions.get(upper)
            if relais:
                relais.write_target(upper == action)  # True when capital letter
            else:
                self._wait = int(action) - 1
                self._pos += i + 1
                return
