import sys
import logging
import asyncio
import nest_asyncio
nest_asyncio.apply()
import threading
import queue
#import janus
from tqdm import tqdm
import os

from epics import caput, caget, cainfo, PV
import epics
import numpy as np

from .const import (EOS_CHAR, ACK_CHAR, NAK_CHAR, FAULT_CHAR, TIMEOUT_CHAR,
                    Drives, Variables, Commands, ScopeData, ScopeStatusType,
                    DataCollectionMask, TaskState, AxisStatus, AxisFault)
from .exceptions import (FailureResponseException, FaultResponseException,
                         TimeoutResponseException, UnknownResponseException,
                         WriteFailureException,
                         )

# from .ws_common import (ScopeConstants)


logger = logging.getLogger(__name__)

aerotechPath = os.path.realpath(os.path.dirname(sys.argv[0]))
os.chdir(aerotechPath)

sys.path.append('../')



import aerotech.globals as globals

def _normalize_axis(axis):
    if isinstance(axis, str):
        return axis
    elif isinstance(axis, int):
        return '@{}'.format(axis)
    raise ValueError('Unexpected axis type (specify name or number)')


class EnsembleGlobal:
    def __init__(self, comm, index, *, check=False):
        self._comm = comm
        self._index = index
        self.check = check

    async def get(self):
        '''Get the value of the global variable'''
        ...

    async def set(self, value, *, check=None):
        '''Set the value of the global variable'''
        ...

    @property
    def index(self):
        '''Global variable index'''
        return self._index

    def __repr__(self):
        return '{}(index={})'.format(type(self).__name__, self._index)


class EnsembleGlobalInt(EnsembleGlobal):
    
    '''Ensemble IGLOBAL'''
    # TO BE FIXED 08/01/2024
    async def get(self):
        # logger.debug('In get function')
        data = self._comm.write_read('IGLOBAL({})'.format(self._index))
        try:
            globals.initialize_loop(asyncio.get_event_loop())
        except RuntimeError:
            globals.initialize_loop(asyncio.get_running_loop())

        if asyncio.iscoroutine(data):
            # data = (globals.loop).run_until_complete(data)
            data = asyncio.run(data)

        #data = await self._comm.write_read('IGLOBAL({})'.format(self._index))
        #logger.debug('Data: %d', int(data))
        return int(data)

    async def set(self, value: int, *, check=None):
        # logger.debug('In set function')
        if check is None:
            check = self.check

        try:
            globals.initialize_loop(asyncio.get_event_loop())
        except RuntimeError:
            globals.initialize_loop(asyncio.get_running_loop())

        value = int(value)
        # logger.debug('Value inside set function: %d', int(value))

        coro = self._comm.write_read('IGLOBAL({}) = {}'.format(self._index, value))

        globals.initialize_loop(asyncio.get_event_loop())
        if asyncio.iscoroutine(coro):
            # (globals.loop).run_until_complete(coro)
            coro = asyncio.run(coro)

        #await self._comm.write_read('IGLOBAL({}) = {}'.format(self._index, value))

        if check:
            read_value = self.get()
            # logger.debug('getting: ', read_value)
            
            globals.initialize_loop(asyncio.get_event_loop())
            if asyncio.iscoroutine(read_value):
                # read_value = (globals.loop).run_until_complete(read_value)
                read_value = asyncio.run(read_value)
                # logger.debug('read value is: ', read_value)
                return read_value

            #read_value = await self.get()

            if read_value != value:
                raise WriteFailureException(value, read_value)
            return read_value


class EnsembleGlobalDouble(EnsembleGlobal):
    '''Ensemble DGLOBAL'''
    float_tolerance = 0.0001

    async def get(self):
        data = self._comm.write_read('DGLOBAL({})'.format(self._index))
        globals.initialize_loop(asyncio.get_event_loop())
        if asyncio.iscoroutine(data):
            data = (globals.loop).run_until_complete(data)

        #data = await self._comm.write_read('DGLOBAL({})'.format(self._index))
#        logger.debug('Data: %f', data)
        return float(data)

    async def dglobal_set(self, value: float, *, check=None):
        if check is None:
            check = self.check

        value = float(value)

        coro = self._comm.write_read('DGLOBAL({}) = {}'.format(self._index, value))
        globals.initialize_loop(asyncio.get_event_loop())
        if asyncio.iscoroutine(coro):
            (globals.loop).run_until_complete(coro)

        #await self._comm.write_read('DGLOBAL({}) = {}'.format(self._index, value))
        if check:
            read_value = self.get()
            globals.initialize_loop(asyncio.get_event_loop())
            if asyncio.iscoroutine(read_value):
                read_value = (globals.loop).run_until_complete(read_value)

            #read_value = await self.get()
            if abs(read_value - value) > self.float_tolerance:
                raise WriteFailureException(value, read_value)
            return read_value


class EnsembleComm:
    def __init__(self, host, port, *, loop=None):
        self.host = host
        self.port = int(port)

        if loop is None:
            try:
                # loop = asyncio.get_event_loop()
                loop = asyncio.get_running_loop()
            except RuntimeError:
                loop = asyncio.new_event_loop()
                asyncio.set_event_loop(loop)

        self.loop = loop

        self._reader = None
        self._writer = None
        self._dglobals = {}
        self._iglobals = {}

    async def _open_connection(self):
        if self._reader is not None:
            return

        # r_w = asyncio.open_connection(self.host, self.port,
        #                                     loop=self.loop)
        # if asyncio.iscoroutine(r_w):
        #     r_w = (self.loop).run_until_complete(r_w)

        # #r_w = await asyncio.open_connection(self.host, self.port,
        #                                     #loop=self.loop)
        # self._reader, self._writer = r_w
        self._reader, self._writer = await asyncio.open_connection(self.host, self.port)


    async def close(self):
        if self._reader is None:
            return

        self._writer.close()
        self._reader = None
        self._writer = None

    async def _write(self, line):
        coro = self._open_connection()
        if asyncio.iscoroutine(coro):
            (self.loop).run_until_complete(coro)

        #await self._open_connection()
        if EOS_CHAR not in line:
            line = ''.join((line, EOS_CHAR))

        self._writer.write(line.encode('latin-1'))

    # TO BE FIXED 08/01/2024
    async def write_read(self, line):
        coro = self._open_connection()
        if asyncio.iscoroutine(coro):
            (self.loop).run_until_complete(coro)

        #await self._open_connection()

        # logger.debug('Line: %s', line) # 07/19/2024 update

        if EOS_CHAR not in line:
            line = ''.join((line, EOS_CHAR))
            # logger.debug('Line in if statement: %s', line) # 07/19/2024 update

        encoded = line.encode('latin-1')
        # logger.debug('Line: %s', line) # 07/19/2024 update
        self._writer.write(line.encode('latin-1'))

        read = ''
        # logger.debug('Read empty: %s', read)
        while EOS_CHAR not in read:
            #que = queue.Queue()
            #originalRead = janus.Queue(1)
            #async_thread = threading.Thread(target=self.async_main, args=(originalRead.async_q,))
            #async_thread.daemon = True
            #Thread3 = threading.Thread(target=lambda q, arg1: q.put(asyncio.run(arg1)), args=(que, self._reader.read(4096)))
            #Thread3 = threading.Thread(target=asyncio.run, args=(self._reader.read(4096),))
            #Thread3.start()
            #Thread3.join()
            #originalReadResult = que.get()
            #originalReadResult = originalRead.async_q.get()
            #print(originalReadResult)
            #originalRead = Thread3.value
            originalRead = self._reader.read(4096)
            #coro = originalRead.decode('latin-1')
            if asyncio.iscoroutine(originalRead):
                originalRead = (self.loop).run_until_complete(originalRead)
                read += originalRead.decode('latin-1')
                #read += (self.loop).run_until_complete(coro)

            #coro = (originalReadResult.decode('latin-1'))
            #if asyncio.iscoroutine(coro):
                #read += (self.loop).run_until_complete(coro)
            #read += originalRead.decode('latin-1')
            #read += originalReadResult.decode('latin-1')
            #read += (await self._reader.read(4096)).decode('latin-1')
            #logger.debug('Read: %s', read)
            #logger.info('Read: %s', read)

        code, response = read[0], read[1:]
        # logger.debug('Wroteeee: %r \n Read: codeddd=%s RESPONSE=%r', line, code,
        #              response)

        if code == ACK_CHAR:
            return response
        elif code == NAK_CHAR:
            #code = '%'
            #response = "0\n"
            #return response
            raise FailureResponseException(response)
        elif code == FAULT_CHAR:
            raise FaultResponseException(response)
        elif code == TIMEOUT_CHAR:
            raise TimeoutResponseException(response)

        raise UnknownResponseException(code, response)
    
    def async_main(self):
        asyncio.run(self._reader.read(4096))

    def iglobal(self, num) -> EnsembleGlobalInt:
        '''Get an EnsembleGlobalInt instance corresponding to an index'''

        # logger.debug('In iglobal function\n')
        

        try:
            #logger.info('self._iglobals: %s\n', self._iglobals)
            return self._iglobals[num]
        except KeyError:
            var = EnsembleGlobalInt(self, num)
            self._iglobals[num] = var

            # logger.debug('self._iglobals: %s\n', self._iglobals)

            return var

    def dglobal(self, num) -> EnsembleGlobalDouble:
        '''Get an EnsembleGlobalDouble instance corresponding to an index'''
        try:
            return self._dglobals[num]
        except KeyError:
            var = EnsembleGlobalDouble(self, num)
            self._dglobals[num] = var
            return var

    async def get_task_state(self, task_number):
        '''Get the TaskState of a specific task number'''
        task_state = self.write_read('TASKSTATE({})'.format(task_number))
        if asyncio.iscoroutine(task_state):
            task_state = (self.loop).run_until_complete(task_state)

        #task_state = await self.write_read('TASKSTATE({})'.format(task_number))
        return TaskState(int(task_state))

    async def run_program(self, task_number, program_name):
        '''Run a program on a specific task number'''
        # logger.debug('Start to runnnnnnnn %r on task %s', program_name, task_number)

        coro = self.write_read('PROGRAM RUN {}, "{}"'
                              ''.format(task_number, program_name))

        if asyncio.iscoroutine(coro):
            (self.loop).run_until_complete(coro)
        #await self.write_read('PROGRAM RUN {}, "{}"'
                              #''.format(task_number, program_name))

    async def stop_task(self, task_number):
        '''Stop a specific task'''
        # logger.debug('Stopping task %s', task_number)

        coro = self.write_read('PROGRAM STOP {}'.format(task_number))

        if asyncio.iscoroutine(coro):
            (self.loop).run_until_complete(coro)

        #await self.write_read('PROGRAM STOP {}'.format(task_number))

    async def ensure_task(self, task_number, program_name):
        '''Ensure a program is running on a specific task number

        If the task is already running, this will be a no-operation.
        If the task has errored, it will first be stopped.
        There is no check to see if the correct program is running.
        '''
        state = self.get_task_state(task_number)

        # logger.debug('Getting task state')
        if asyncio.iscoroutine(state):
            state = (self.loop).run_until_complete(state)

        #state = await self.get_task_state(task_number)


        if state in (TaskState.running, ):
            # Task is already running
            # logger.debug('Task %s is RUNNING !!!', task_number)
            pass
        elif state in (TaskState.idle, TaskState.ready, TaskState.paused,
                       TaskState.done, TaskState.errored):
            if state == TaskState.errored:
                # logger.debug('Task %s has errored; stopping it', task_number)

                coro = self.stop_task(task_number)
                if asyncio.iscoroutine(state):
                    (self.loop).run_until_complete(coro)

                #await self.stop_task(task_number)

                coro = asyncio.sleep(0.1)
                if asyncio.iscoroutine(coro):
                    (self.loop).run_until_complete(coro)

                #await asyncio.sleep(0.1)
            elif state == TaskState.idle:
                logger.debug('Task %s is IDLE!!!', task_number)
            elif state == TaskState.ready:
                logger.debug('Task %s is READY!!!', task_number)
            elif state == TaskState.paused:
                logger.debug('Task %s is PAUSED!!!', task_number)
            elif state == TaskState.done:
                logger.debug('Task %s is DONE!!!', task_number)

            coro = self.run_program(task_number, program_name)
            if asyncio.iscoroutine(coro):
                (self.loop).run_until_complete(coro)

            #await self.run_program(task_number, program_name)

    async def reset(self):
        logger.debug('Resetting')

        coro = self._write('RESET')
        if asyncio.iscoroutine(coro):
            (self.loop).run_until_complete(coro)

        #await self._write('RESET')

    async def commit_parameters(self, *, reset=False):
        logger.debug('Committing parameters...')

        coro = self.write_read('COMMITPARAMETERS')
        if asyncio.iscoroutine(coro):
            (self.loop).run_until_complete(coro)

        #await self.write_read('COMMITPARAMETERS')

        if reset:
            coro = self.reset()
            if asyncio.iscoroutine(coro):
                (self.loop).run_until_complete(coro)
            #await self.reset()

    async def acknowledge_all(self, *, reset=False):
        logger.debug('Acknowledge all...')

        coro = self.write_read('ACKNOWLEDGEALL')
        if asyncio.iscoroutine(coro):
            (self.loop).run_until_complete(coro)

        #await self.write_read('ACKNOWLEDGEALL')

        if reset:
            coro = self.reset()
            if asyncio.iscoroutine(coro):
                (self.loop).run_until_complete(coro)
            #await self.reset()

    async def get_axis_status(self, axis):
        axis = _normalize_axis(axis)

        status = self.write_read('AXISSTATUS {}'.format(axis))
        if asyncio.iscoroutine(status):
            status = (self.loop).run_until_complete(status)

        #status = await self.write_read('AXISSTATUS {}'.format(axis))
        return AxisStatus(int(status))

    async def get_axis_fault_status(self, axis):
        axis = _normalize_axis(axis)

        fault = self.write_read('AXISFAULT {}'.format(axis))
        if asyncio.iscoroutine(fault):
            fault = (self.loop).run_until_complete(fault)

        #fault = await self.write_read('AXISFAULT {}'.format(axis))
        return AxisFault(int(fault))

    async def move(self, axis_position_pairs: dict, *, speed, absolute):
        axis_pos = ('{} {}'.format(_normalize_axis(axis), position)
                    for axis, position in axis_position_pairs.items())
        cmd = 'MOVE{} {} F{}'.format('ABS' if absolute else 'INC',
                                     ' '.join(axis_pos), speed)
        logger.debug('Moving: %s', cmd)

        coro = self.write_read(cmd)
        if asyncio.iscoroutine(coro):
            fault = (self.loop).run_until_complete(coro)
        return coro
        #return await self.write_read(cmd)

    async def wait_axis_status(self, axis, flags, *, poll_period=0.01,
                               check_enabled=False):
        while True:
            status = self.get_axis_status(axis)
            if asyncio.iscoroutine(status):
                status = (self.loop).run_until_complete(status)

            #status = await self.get_axis_status(axis)
            if flags in status:
                return True
            elif check_enabled and AxisStatus.Enabled not in status:
                return False

            coro = asyncio.sleep(poll_period)
            if asyncio.iscoroutine(coro):
                (self.loop).run_until_complete(coro)
            #await asyncio.sleep(poll_period)

    async def move_and_wait(self, axis_position_pairs: dict, *,
                            wait_flags=AxisStatus.InPosition, speed, absolute,
                            poll_period=0.01):

        coro = self.move(axis_position_pairs, speed=speed, absolute=absolute)
        if asyncio.iscoroutine(coro):
            (self.loop).run_until_complete(coro)
        #await self.move(axis_position_pairs, speed=speed, absolute=absolute)

        for axis in axis_position_pairs:
            logger.debug('Waiting on axis %s', axis)

            coro = self.wait_axis_status(axis, wait_flags, check_enabled=True,
                                        poll_period=poll_period)

            if asyncio.iscoroutine(coro):
                (self.loop).run_until_complete(coro)
            #await self.wait_axis_status(axis, wait_flags, check_enabled=True,
                                        #poll_period=poll_period)

    async def home(self, axes, wait_flags=AxisStatus.InPosition,
                   poll_period=0.01):
        if isinstance(axes, str):
            axes = [axes]

        coro = self.write_read('HOME {}'.format(' '.join(axes)))
        if asyncio.iscoroutine(coro):
            (self.loop).run_until_complete(coro)

        #await self.write_read('HOME {}'.format(' '.join(axes)))


        for axis in axes:
            logger.debug('Waiting on axis %s', axis)

            coro = self.wait_axis_status(axis, wait_flags, check_enabled=True,
                                        poll_period=poll_period)

            if asyncio.iscoroutine(coro):
                (self.loop).run_until_complete(coro)

            #await self.wait_axis_status(axis, wait_flags, check_enabled=True,
                                        #poll_period=poll_period)


class EnsembleDoCommand(EnsembleComm):
    '''Ensemble running script doCommand.ab/bcx as task #4'''

    task_number = 4
    program_name = 'doCommand.bcx'

    _int_nums = [Variables.int_arg1, Variables.int_arg2, Variables.int_arg3,
                 Variables.int_arg4,
                 ]
                # IGLOBAL(46), IGLOBAL(47), IGLOBAL(48), IGLOBAL(49)

    _double_nums = [Variables.double_arg1, Variables.double_arg2,
                    Variables.double_arg3, Variables.double_arg4,
                    Variables.double_arg5, Variables.double_arg6,
                    Variables.double_arg7, Variables.double_arg8,
                    Variables.double_arg9,
                    ]
    #             DGLOBAL(1) through (9)

    
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        logger.debug('Host !!!: %s', self.host)
        logger.debug('Port !!!: %d', self.port)
        logger.debug('Loop !!!: %s', self.loop)

        self._int_args = [EnsembleGlobalInt(self, idx)
                          for idx in self._int_nums]
        self._double_args = [EnsembleGlobalDouble(self, idx)
                             for idx in self._double_nums]
        # logger.debug('_int_args: %s', self._int_args)
        # logger.debug('_double_args: %s', self._double_args)	

    async def check_program_status(self):
        # '''Start doCommand.bcx if not already running'''
        '''Start ws_scope_data.ab if not already running'''

        print('check_program_status')
        coro = self.ensure_task(self.task_number, self.program_name)
        if asyncio.iscoroutine(coro):
            (self.loop).run_until_complete(coro)

        #await self.ensure_task(self.task_number, self.program_name)
        return True

                                                    ## (null) 07/20/2024: command: Commands changes to request: ScopeData
    async def write_command(self, command: Commands, *, wait=True,
                            int_args=None, double_args=None):
        
        if int_args is not None:
            for arg, value in zip(self._int_args, int_args):
                coro = arg.set(value)
                if asyncio.iscoroutine(coro):
                    (self.loop).run_until_complete(coro)
                #await arg.set(value)

        if double_args is not None:
            for arg, value in zip(self._double_args, double_args):
                coro = arg.set(value)
                if asyncio.iscoroutine(coro):
                    (self.loop).run_until_complete(coro)
                #await arg.set(value)

        # logger.debug('_int_args: %s', int_args)
        # logger.debug('_double_args: %s', double_args)

        cmd_arg = self.iglobal(Variables.command)       #Variable.command = 45 for iglobal(45)
                                                       
        # logger.debug('cmd_arg: %s', cmd_arg)
        # logger.debug('Command: %d\n', command)
        # logger.debug('Index: %s\n', cmd_arg.index)
                                                                       
        coro = cmd_arg.set(command, check=False)
        if asyncio.iscoroutine(coro):
            (self.loop).run_until_complete(coro)

        #await cmd_arg.set(command, check=False)
        # await cmd_arg.get()

        # logger.debug('Wait: %s', wait)
        # logger.debug('Command: %d\n', command)

        if wait and command != Commands.do_trajectory:
            while True:
                value = cmd_arg.get()
                if asyncio.iscoroutine(value):
                    value = (self.loop).run_until_complete(value)
                #value = await cmd_arg.get()
                # logger.debug('Valueeeeee: %d', value)
                # logger.debug('Commanddddd: %d', command)
                
                if value == command:
                    break

                coro = asyncio.sleep(0.001)
                if asyncio.iscoroutine(coro):
                    (self.loop).run_until_complete(coro)
                    # 07/15/2024

                if value <= 0 :
                    print("VALUE IS NEGATIVE")
                    break

                #await asyncio.sleep(0.001)

    async def read_drive_info(self):
        logger.debug('Into read drive info function')

        coro = self.write_command(Commands.drive_info)
        if asyncio.iscoroutine(coro):
            (self.loop).run_until_complete(coro)
        #await self.write_command(Commands.drive_info)

        logger.debug('Done with write_command function')

        drive = self._int_args[0].get()
        if asyncio.iscoroutine(drive):
            drive = (self.loop).run_until_complete(drive)
        #drive = await self._int_args[0].get()
        logger.debug('Drive: %s', drive)
        try:
            return Drives(drive)
        except TypeError:
            logger.error('Unknown drive type: %d', drive)
            return drive

    async def scope_start(self, data_points, period_ms):
        coro = self.scope_stop()
        if asyncio.iscoroutine(coro):
            # print('SCOPE STOP INPUT PROCESSING')
            (self.loop).run_until_complete(coro)
        #await self.scope_stop()

        coro = self.write_command(Commands.scope_buffer,
                                 int_args=[data_points])
        if asyncio.iscoroutine(coro):
            # print('SCOPE BUFFER COMMAND INPUT PROCESSING')
            (self.loop).run_until_complete(coro)
        #await self.write_command(Commands.scope_buffer,
                                 #int_args=[data_points])

        coro = self.write_command(Commands.scope_trigger_period,
                                 int_args=[period_ms])
        if asyncio.iscoroutine(coro):
            # print('SCOPE TRIG PERIOD INPUT PROCESSING')
            (self.loop).run_until_complete(coro)

        #await self.write_command(Commands.scope_trigger_period,
                                 #int_args=[period_ms])

        coro = self.write_command(Commands.scope_trigger,
                                 int_args=[0])
        if asyncio.iscoroutine(coro):
            # print('SCOPE TRIGGER INPUT PROCESSING')
            (self.loop).run_until_complete(coro)
        #await self.write_command(Commands.scope_trigger,
                                 #int_args=[0])
        max_points = self.get_scope_max_points()
        if asyncio.iscoroutine(max_points):
            max_points = (self.loop).run_until_complete(max_points)
        #max_points = await self.get_scope_max_points()

        allocated = self.get_scope_points_allocated()
        if asyncio.iscoroutine(allocated):
            allocated = (self.loop).run_until_complete(allocated)
        #allocated = await self.get_scope_points_allocated()

        collected = self.get_scope_points_collected()
        if asyncio.iscoroutine(collected):
            collected = (self.loop).run_until_complete(collected)
        #collected = await self.get_scope_points_collected()

        # logger.info('Max points: %d', max_points)
        # logger.info('Allocated: %d', allocated)
        # logger.info('Collected: %d', collected)

        # logger.debug('Scope configured with period %d ms / '
        #              'collected %d allocated: %d of max %d',
        #              period_ms, collected, allocated, max_points)

    async def scope_stop(self):
        coro = self.write_command(Commands.scope_trigger,
                                 int_args=[1])
        if asyncio.iscoroutine(coro):
            (self.loop).run_until_complete(coro)
        #await self.write_command(Commands.scope_trigger,
                                 #int_args=[1])

    async def get_scope_status(self, *,
                               type_=ScopeStatusType.collection_status):
        coro = self.write_command(Commands.scope_status, int_args=[type_])
        if asyncio.iscoroutine(coro):
            (self.loop).run_until_complete(coro)

        #await self.write_command(Commands.scope_status, int_args=[type_])
        coro = self._int_args[0].get()
        if asyncio.iscoroutine(coro):
            return (self.loop).run_until_complete(coro)
        #return await self._int_args[0].get()

    async def get_scope_max_points(self):
        coro = self.get_scope_status(type_=ScopeStatusType.max_points)
        if asyncio.iscoroutine(coro):
            return (self.loop).run_until_complete(coro)
        #return await self.get_scope_status(type_=ScopeStatusType.max_points)

    async def get_scope_points_allocated(self):
        coro = await self.get_scope_status(
            type_=ScopeStatusType.points_allocated)
        if asyncio.iscoroutine(coro):
            return (self.loop).run_until_complete(coro)
        #return await self.get_scope_status(
            #type_=ScopeStatusType.points_allocated)

    async def get_scope_points_collected(self):
        coro = await self.get_scope_status(
            type_=ScopeStatusType.points_collected)
        if asyncio.iscoroutine(coro):
            return (self.loop).run_until_complete(coro)
        #return await self.get_scope_status(
            #type_=ScopeStatusType.points_collected)

    async def fast_get_scope_data(self, data_points, data_key: ScopeData, downsample = int):

        data = []
        
        max_points = len(self._double_args)  # == 9                           
        damped_points = (max_points / downsample)                               
        damped_points = int(damped_points)

        # print(f" !!!... MAX POINTS: {max_points} \n !!!... DAMPED POINTS: {damped_points} \n")
        coro = self.write_command(  Commands.fast_scope_data,
                                    int_args=[data_key, 0, damped_points], 
                                    double_args=[0.0],                      
                                 )
        
        if asyncio.iscoroutine(coro):
            (self.loop).run_until_complete(coro)

        data_key_var, data_point_var, num_points_var = self._int_args[:3]   


        for i in range(0, data_points, damped_points):         
            
            num_to_read = min((damped_points, data_points - i))
            data_args = self._double_args[:num_to_read]

            coro = data_point_var.set(i)

            if asyncio.iscoroutine(coro):
                (self.loop).run_until_complete(coro)
                # await data_point_var.set(i)

            if num_to_read != damped_points:
                coro = num_points_var.set(num_to_read)
                if asyncio.iscoroutine(coro):
                    (self.loop).run_until_complete(coro)
                    # await num_points_var.set(num_to_read)
        
            coro = self.write_command(Commands.fast_scope_data)

            if asyncio.iscoroutine(coro):
                (self.loop).run_until_complete(coro)
                # await self.write_command(Commands.fast_scope_data)
        
            for dvar in data_args:
                value = dvar.get()
                if asyncio.iscoroutine(value):
                    value = (self.loop).run_until_complete(value)
                data.append(value)
 
        return data

#-------------------------------------------------------------------------------------------------------------------------------------------------------
class EnsembleScopeWS(EnsembleComm):
    '''Ensemble running script ws_scope_data.ab as task #3'''
    
    task_number = 3
    program_name = 'ws_scope_data.ab'

    _int_nums = [Variables.ireg_downsample, Variables.ireg_scope_data_request, Variables.ireg_scope_data_length, Variables.ireg_loop
                
                 ]
    _double_nums = [Variables.double_arg1, Variables.double_arg2,
                    Variables.double_arg3, Variables.double_arg4,
                    Variables.double_arg5, Variables.double_arg6,
                    Variables.double_arg7, Variables.double_arg8,
                    Variables.double_arg9
                    ]
    
    
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        # logger.critical('Host: %s', self.host)
        # logger.critical('Port: %d', self.port)
        # # logger.critical('Loop: %s', self.loop)

        self._int_args = [EnsembleGlobalInt(self, idx)
                          for idx in self._int_nums]
        self._double_args = [EnsembleGlobalDouble(self, idx)
                             for idx in self._double_nums]
        # logger.debug('_int_args: %s', self._int_args)
        # logger.debug('_double_args: %s', self._double_args)	

    float_tolerance = 0.0001

    async def get(self):
        data = self._comm.write_read('DGLOBAL({})'.format(self._index))
        globals.initialize_loop(asyncio.get_event_loop())
        if asyncio.iscoroutine(data):
            data = (globals.loop).run_until_complete(data)

        return float(data)

    async def check_program_status(self):
        '''Start ws_scope_data.ab if not already running'''

        coro = self.ensure_task(self.task_number, self.program_name)
        if asyncio.iscoroutine(coro):
            (self.loop).run_until_complete(coro)

        return True

    async def scope_acquisition(self, request: ScopeData, *, wait=True, int_args=None, double_args=None):

        if int_args is not None:
            for arg, value in zip(self._int_args, int_args):
                coro = arg.set(value)
                if asyncio.iscoroutine(coro):
                    (self.loop).run_until_complete(coro)
                #await arg.set(value)

        if double_args is not None:
            for arg, value in zip(self._double_args, double_args):
                coro = arg.set(value)
                if asyncio.iscoroutine(coro):
                    (self.loop).run_until_complete(coro)


        cmd_arg = self.iglobal(Variables.ireg_scope_data_request)       

        coro = cmd_arg.set(request, check=False)
        if asyncio.iscoroutine(coro):
            (self.loop).run_until_complete(coro)


        if wait and request > 0:
            while True:
                value = cmd_arg.get()
                if asyncio.iscoroutine(value):
                    value = (self.loop).run_until_complete(value)

                if value == request:
                    break

                coro = asyncio.sleep(0.001)
                if asyncio.iscoroutine(coro):
                    (self.loop).run_until_complete(coro)
                    
                if value <= 0 :
                    print("VALUE IS NEGATIVE")
                    break

    async def ws_write_read(self, line):
        coro = self._open_connection()
        if asyncio.iscoroutine(coro):
            (self.loop).run_until_complete(coro)


        if EOS_CHAR not in line:
            line = ''.join((line, EOS_CHAR))

        encoded = line.encode('latin-1')

        self._writer.write(line.encode('latin-1'))

        read = ''

        while EOS_CHAR not in read:
          
            originalRead = self._reader.read(4096)

            if asyncio.iscoroutine(originalRead):
                originalRead = (self.loop).run_until_complete(originalRead)
                read += originalRead.decode('latin-1')


        code, response = read[0], read[1:]
        # logger.debug('Wroteeee: %r \n Read: codeddd=%s RESPONSE=%r', line, code,
                    #  response)

        if code == ACK_CHAR:
            return response
        elif code == NAK_CHAR:
            #code = '%'
            #response = "0\n"
            #return response
            raise FailureResponseException(response)
        elif code == FAULT_CHAR:
            raise FaultResponseException(response)
        elif code == TIMEOUT_CHAR:
            raise TimeoutResponseException(response)

        raise UnknownResponseException(code, response)

    async def dglobal_pull_new(self, ds_num = int):
        # -> UNSTABLE, TO BE FIXED
        
        # -> directly implement data_points and downsample data parameters
        iglobal99 = self.iglobal(99)
        data_points = await iglobal99.get()
        iglobal97 = self.iglobal(97)
        downsample = await iglobal97.get()

        # -> downsampled length of data array
        downlen = int(data_points/downsample) 
        dat_cnt = int(ds_num*downlen)

        # -> generate time and data arrays
        time_array = np.arange(0, data_points , downsample)
        data_array = []

        # -> pull Aerotech dglobals based on downsampled length input
        for i in range(ds_num, downlen + ds_num, 1):

            if ds_num == 0:
                dglobal_val = self.dglobal(i + 100 ) 
                data_value = await dglobal_val.get()
                data_array.append(data_value)
                progress = len(data_array)
                if len(data_array) == len(time_array):
                    break
            else: #-> TO BE FIXED...
                dglobal_val = self.dglobal(i + 101 + int(ds_num*downlen)) 
                data_value = await dglobal_val.get()
                data_array.append(data_value)
                progress = len(data_array)
                if len(data_array) == len(time_array):
                    break

        # logger.debug('length of data_array: ', len(data_array))
        # logger.debug('length of time array: ', len(time_array))

        # -> if outputs are unequal length by one value
        if len(data_array) > len(time_array):
            data_array = data_array[:-1]
            time_array = time_array
        elif len(data_array) < len(time_array):
            time_array = time_array[:]

        elif len(data_array) == len(time_array):
            data_array = data_array
            time_array = time_array

        return data_array, progress, time_array
    
    async def epics_PV(self, scanner, data_list, data_type):
        # -> UNSTABLE, TO BE FIXED

        # -> data_type: 'TIME' , 'POSCMD', 'POSFDBK', 'ICMD', 'IFDBK'
        
        epics_list = PV(f'{scanner}:SCOPEDATA:{data_type}')
        epics_list.put(data_list) 
        # epics_list_max = epics.caget(f'{scanner}:SCOPEDATA:MAX{data_type}').max()
        
        return epics_list #, epics_list_max

    
