#!/usr/bin/env python
# Mendez 2014.06
# gives a prompt to run a set of commands e.g.:
#   > az move -9  # move azimuth in negative direction at high speed
#   > az move 3   # move azimuth in pos diretion at speed=3
#   > at pos_move 1 # move altitude in positive direction
#   > at version # get the version of the at microcontroller
#   > at 254     # pass in a decimal code for a command (version)
# See graffito.telescope.COMMANDS for known ones.


import sys
import os
import readline
from graffito import telescope

# TODO: replace with argparse or something.
# DEVICE = (sys.argv[1] if len(sys.argv)==2 else None)
print len(sys.argv)
DEVICE = (sys.argv[1] if ((len(sys.argv)>=2) and (os.path.exists(sys.argv[1])) ) else None)
DEBUG  = ('debug' in sys.argv)

def parsedata(cmd):
    '''parse the data anything above the second command.'''
    try:
        return map(int, cmd[2:])
    except:
        return None

def parseint(c):
    '''Parse as an integer -- returns the string if not able to parse'''
    try:
        return int(c)
    except:
        return c


def main():
    '''Interactive prompt for commands injection.
        > az move -9  # move azimuth in negative direction at high speed
        > az move 3   # move azimuth in pos diretion at speed=3
        > at pos_move 1 # move altitude in positive direction
        > at version # get the version of the at microcontroller
        > at 254     # pass in a decimal code for a command (version)
    See graffito.telescope.COMMANDS for known ones.
    '''
    with telescope.Telescope(device=DEVICE) as tele:
        print 'Configured with {}'.format(tele.port)
        while True:
            try:
                usercmd = raw_input('> ')
                if usercmd in ['exit', 'quit', 'q']:
                    return
                if len(usercmd) == 0:
                    output = tele.get()
                    if output:
                        tele.niceprint(output, showcmd=True)
                    continue
                
                tmp = (usercmd.replace(',','')
                              .replace('[','')
                              .replace(']','')
                              .split(' ') )
                axis, command = map(parseint, tmp[:2])
                data = parsedata(tmp)
                packet = tele.craft(axis, command, data)
                print 'running: {}'.format(packet)
                output = tele._run(packet)
                if output:
                    print tele.niceprint(output, showcmd=True)
            
            except KeyboardInterrupt as e:
                print ' ! Goodbye'
                return
            
            except Exception as e:
                print e
                print ' ! Failed to craft '
                if DEBUG:
                    raise
                



if __name__ == '__main__':
    if DEBUG:
        from pysurvey import util
        util.setup_stop()
    
    main()