# Path: timestream/util/layouts.py
# def traypos_to_chamber_index(traypos, tray_cap=20, col_cap=5):
#     if not isinstance(traypos, str):
#         msg = PARAM_TYPE_ERR.format(func='traypos_to_chamber_index',
#                                     param='traypos', type='str')
#         LOG.error(msg)
#         raise TypeError(msg)
#     extractor = re.compile(r'^(\d{1,2})([a-zA-Z])([1-9])$')
#     match = extractor.match(traypos)
#     if match is None:
#         msg = "Tray Pos '{}' is invalid".format(traypos)
#         LOG.error(msg)
#         raise ValueError(msg)
#     tray, col, row = match.groups()
#     tray = int(tray)
#     col = ord(col.upper()) - 65  # Numericise the col num, 0-based
#     row = int(row)
#     index = (tray - 1) * tray_cap + col * col_cap + row
#     return index


import csv
from docopt import docopt
from timestream.util.layouts import traypos_to_chamber_index


CLI_DOC = """
USAGE:
    fixChamberPos.py [-n] -c COLUMN -i INPUT

OPTIONS:
    -n          CSV has no header
    -c COLUMN   Column to convert.
    -i INPUT    Input CSV

"""

def main(opts):
    ifh = open(opts['-i'])
    rdr = csv.reader(ifh)
    col = int(opts['-c']) - 1
    if not opts['-n']:
        print(','.join(next(rdr)))
    for line in rdr:
        if col < 0 or col > len(line) - 1:
            print "Invalid column", opts['-c']
            exit(1)

# Path: timestream/util/layouts.py
# def traypos_to_chamber_index(traypos, tray_cap=20, col_cap=5):
#     if not isinstance(traypos, str):
#         msg = PARAM_TYPE_ERR.format(func='traypos_to_chamber_index',
#                                     param='traypos', type='str')
#         LOG.error(msg)
#         raise TypeError(msg)
#     extractor = re.compile(r'^(\d{1,2})([a-zA-Z])([1-9])$')
#     match = extractor.match(traypos)
#     if match is None:
#         msg = "Tray Pos '{}' is invalid".format(traypos)
#         LOG.error(msg)
#         raise ValueError(msg)
#     tray, col, row = match.groups()
#     tray = int(tray)
#     col = ord(col.upper()) - 65  # Numericise the col num, 0-based
#     row = int(row)
#     index = (tray - 1) * tray_cap + col * col_cap + row
#     return index


# Path: scripts/tscli/fixChamberPos.py
import csv
from docopt import docopt
from timestream.util.layouts import traypos_to_chamber_index



CLI_DOC = """
USAGE:
    fixChamberPos.py [-n] -c COLUMN -i INPUT

OPTIONS:
    -n          CSV has no header
    -c COLUMN   Column to convert.
    -i INPUT    Input CSV

"""

def main(opts):
    ifh = open(opts['-i'])
    rdr = csv.reader(ifh)
    col = int(opts['-c']) - 1
    if not opts['-n']:
        print(','.join(next(rdr)))
    for line in rdr:
        if col < 0 or col > len(line) - 1:
            print "Invalid column", opts['-c']
            exit(1)

        line[col] = str(traypos_to_chamber_index(line[col]))