# *****************************************************************************
# 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: Oksana Shliakhtun <oksana.shliakhtun@psi.ch>
# *****************************************************************************
"""Keithley Instruments 2601B-PULSE System (not finished)"""

from frappy.core import StringIO, HasIO, Readable, Writable, \
    Parameter, FloatRange, EnumType


class PulseIO(StringIO):
    end_of_line = '\n'
    identification = [('*IDN?', 'Keithley Instruments, Model 2601B-PULSE,.*')]


class Base(HasIO):
    ioClass = PulseIO

    def set_source(self):
        """
        Set the source -always current
        :return:
        """
        return self.communicate(f'smua.source.func = smua.OUTPUT_DCAMPS')

    def get_par(self, cmd):
        return self.communicate(f'reading = smua.measure.{cmd}()')

    def auto_onof(self, val):
        if val == 1:
            return f'smua.AUTORANGE_ON'
        if val == 0:
            return f'smua.AUTORANGE_OFF'

    def set_measure(self, cmd, val):
        return self.communicate(f'smua.measure.{cmd} = {val}')


class Create_Pulse(Base, Writable):
    target = Parameter('source target', FloatRange, unit='A', readonly=False)
    width = Parameter('pulse width', FloatRange, unit="s", readonly=False)
    resistance = Parameter('resistance', FloatRange)

    SOURCE_RANGE = ['100nA', '1uA', '10uA', '100uA', '1mA', '10mA', '100mA', '1A', '3A']
    range = Parameter('source range', EnumType('source range',
                                               {name: idx for idx, name in enumerate(SOURCE_RANGE)}), readonly=False)

    def read_range(self):
        return self.range

    def write_range(self, range):
        self.communicate(f'smua.source.rangei = {range}')
        return self.range

    def write_target(self, target):
        return self.communicate(f'smua.source.leveli = {target}')

    def read_resistance(self):
        return self.communicate('reading = smua.measure.r()')


class Script(Create_Pulse):
    pass
