#!/usr/bin/env python
"""Creates the pin file for the Teensy."""

from __future__ import print_function

import argparse
import sys
import csv

SUPPORTED_FN = {
    'FTM'   : ['CH0',  'CH1',  'CH2',  'CH3', 'CH4', 'CH5', 'CH6', 'CH7',
               'QD_PHA', 'QD_PHB'],
    'I2C'   : ['SDA', 'SCL'],
    'UART'  : ['RX', 'TX', 'CTS', 'RTS'],
    'SPI'   : ['NSS', 'SCK', 'MISO', 'MOSI']
}

def parse_port_pin(name_str):
    """Parses a string and returns a (port-num, pin-num) tuple."""
    if len(name_str) < 4:
        raise ValueError("Expecting pin name to be at least 4 charcters.")
    if name_str[0:2] != 'PT':
        raise ValueError("Expecting pin name to start with PT")
    if name_str[2] not in ('A', 'B', 'C', 'D', 'E', 'Z'):
        raise ValueError("Expecting pin port to be between A and E or Z")
    port = ord(name_str[2]) - ord('A')
    pin_str = name_str[3:].split('/')[0]
    if not pin_str.isdigit():
        raise ValueError("Expecting numeric pin number.")
    return (port, int(pin_str))

def split_name_num(name_num):
    num = None
    for num_idx in range(len(name_num) - 1, -1, -1):
        if not name_num[num_idx].isdigit():
            name = name_num[0:num_idx + 1]
            num_str = name_num[num_idx + 1:]
            if len(num_str) > 0:
                num = int(num_str)
            break
    return name, num


class AlternateFunction(object):
    """Holds the information associated with a pins alternate function."""

    def __init__(self, idx, af_str):
        self.idx = idx
        self.af_str = af_str

        self.func = ''
        self.fn_num = None
        self.pin_type = ''
        self.supported = False

        af_words = af_str.split('_', 1)
        self.func, self.fn_num = split_name_num(af_words[0])
        if len(af_words) > 1: