# *****************************************************************************
# 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>
# *****************************************************************************

from frappy.core import StringIO, HasIO, Writable, Parameter, FloatRange, IntRange, \
    IDLE, ERROR
from frappy.errors import CommunicationFailedError
from frappy.ctrlby import WrapControlledBy


class IO(StringIO):
    end_of_line = '\n'
    identification = [('id', 'dilhtr.*')]
    default_settings = {'baudrate': 9600}


class Heater(HasIO, Writable):

    ioClass = IO    # define IO class for automatic creation of the IO module

    target = Parameter('power target value', FloatRange(0, 6e6, unit='W'), readonly=False)
    value = Parameter('power reading', FloatRange(unit='W'))
    resistance = Parameter('resistance reading', FloatRange(unit='Ohm'))
    current = Parameter('curren reading', FloatRange(unit='A'))
    voltage = Parameter('voltage reading', FloatRange(unit='V'))
    range = Parameter('range reading', IntRange(1, 3))

    status_map = {'0' : (IDLE, ''),
                  '1' : (ERROR, 'short circuit'),
                  '2' : (ERROR, 'open circuit')}

    def request(self, code):
        reply, txtvalue = self.communicate(f'{code}').split('=')
        if reply != code:
            raise CommunicationFailedError(f'bad reply: {reply}')
        return float(txtvalue)

    def write_target(self, target):
        self.communicate(f'p={target * 1e6}')   # W to uW

    def read_value(self):
        return self.request('pr') * 1e-6    # uW to W

    def read_resistance(self):
        return self.request('r')

    def read_current(self):
        return self.request('i') * 1e-3     # mA to A

    def read_voltage(self):
        return self.request('v') * 1e-3     # mV to V

    def read_range(self):
        return int(self.request('k'))

    def read_status(self):
        reply, status = self.communicate('h').split('=')
        if reply != 'h':
            raise CommunicationFailedError(f'bad reply from status request: {reply}')
        return self.status_map.get(status, (ERROR, 'bad status'))


class WrappedHeater(WrapControlledBy, Heater):
    pass
