# *****************************************************************************
# 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>
# *****************************************************************************
"""PDLD Laser
----cfg.py example ---
# connected via USB
Mod('laser_io',
    'frappy_psi.pdld.IO',
    'laser IO',
    uri='serial:///dev/ttyUSB1?baudrate=9600',
)

Mod('laser',
    'frappy_psi.pdld.Laser',
    'laser switch',
    io='laser_io',
)

Mod('laser_power',
    'frappy_psi.pdld.LaserPower',
    'laser power',
    io='laser_io',
)
~

"""


from frappy.core import StringIO, Parameter, HasIO, \
    Writable, FloatRange, BoolType, IDLE, ERROR


class IO(StringIO):
    end_of_line = ('>', '\r')


class Laser(HasIO, Writable):
    ioClass = IO
    value = Parameter('on/off', BoolType())
    target = Parameter('on/off', BoolType())

    def get_par(self, cmd):
        return float(self.communicate(cmd).split()[-1])

    def read_value(self):
        reply = float(self.communicate('MCM').split()[-1])
        if reply == 10:
            self.status = IDLE, ''
            return True
        if reply in (0, 40):
            self.status = IDLE, ''
            return False
        return ERROR, 'bad OP mode %s', reply

    def write_target(self, value):
        if value:
            self.communicate('SALO')
        else:
            self.communicate('SALS')


class LaserPower(HasIO, Writable):
    value = Parameter('power readback', FloatRange(unit='mW'))
    target = Parameter('power setpoint', FloatRange(0, 300, unit='mW'), readonly=False)
    ioClass = IO

    def read_value(self):
        return float(self.communicate('MPO').split()[-1])

    def read_target(self):
        return float(self.communicate('MPR').split()[-1])

    def write_target(self, value):
        self.communicate(f'SPR{int(value):03d}')

