# -*- coding: utf-8 -*-
'''Transform data on in a dataport by mapping all values (alpha)

Usage:
    exo [options] transform <cik> <rid> <func>

Command Options:
    --cma
    --start=<time>
    --end=<time>             start and end times (see details below)
    {{ helpoption }}

{{ startend }}
'''

from __future__ import unicode_literals
import re
import os
import csv
import sys

class Plugin():
    def command(self):
        return 'transform'

    def run(self, cmd, args, options):

        cik = options['cik']
        rid = options['rids'][0]
        mapFunc = args['<func>']
        mpfn = eval('lambda x: ' + mapFunc)
        rpc = options['rpc']
        ExoException = options['exception']
        ExoUtilities = options['utils']

        start, end = ExoUtilities.get_startend(args)
        cma = args['--cma']

        # TODO Test using start-end ranges

        # read data in range, get as array of values.
        response = rpc.read(cik, rid, 65535, 'asc', start, end, 'all')
        # response is array of arrays

        if cma:
            with open(cik + '-read.csv', 'wb') as cvsfile:
                cw = csv.writer(cvsfile)
                cw.writerows(response)

        # Rotate response so we can pass an array of values to the map
        rotated = zip(*response[::-1])

        # transform
        res = map(mpfn, rotated[1])
        rotated[1] = res

        # Rotate it back so we can 'record' it
        data = zip(*rotated)

        if cma:
            with open(cik + '-transformed.csv', 'wb') as cvsfile:
                cw = csv.writer(cvsfile)
                cw.writerows(data)

        # FIXME start and end for read and flush mean different things!
        rpc.flush(cik, [rid], start, end)

        # Put the modified values back
        rpc.record(cik, rid, data)


# vim: set ai et sw=4 ts=4 :

@@ -1028,16 +1028,95 @@
 arrays%0A%0A
+        if len(response) == 0:%0A            raise ExoException('No data read')%0A%0A
         

Stop if no data was read.