#!/usr/bin/env python
"""
 This module reads a specified .cmp file generated by kicad and creates
 a csv file that contains extracted data.
"""

import argparse

def cmp_extract_info(component):
    'Extract and return component data'
    description = component.split('\n')
    reference = ''
    value = ''
    footprint = ''

    if(len(description) > 3):
        reference = description[1][12:-1]
        value = description[2][12:-1]
        footprint = description[3][12:-1]

    return reference, value, footprint

def rearrange_table(table_in):
    'Remove duplicates in the table and adds parts count'
    table_out = [[],[],[],[]]
    table = zip(*table_in)  # Flip table

    for item in table_in:
        # If the component is listed, add the reference
        if(item[1] in table_out[1] and item[2] in table_out[2]):
            cmp_index = table_out[1].index(item[1])
            table_out[0][cmp_index] += ' %s' % item[0]
            table_out[3][cmp_index] = str(int(table_out[3][cmp_index]) + 1)
        # Else add the component
        else:
            table_out[0].append(item[0])
            table_out[1].append(item[1])
            table_out[2].append(item[2])
            table_out[3].append('1')

    table_out = zip(*table_out)
    return table_out

def main():
    'Where the magic happens'
    # Arguments parsing
    parser = argparse.ArgumentParser(description='Convert kicad cmp file to a BOM')
    parser.add_argument('filename_input', metavar='Fin', type=str, \
                        help='Input file name')
    args = parser.parse_args()

    # Open input cmp file
    filename_input = args.filename_input
    f_in = open(filename_input, 'r')
    # Open output csv file
    filename_output = '%s-bom.csv' % filename_input.split('.')[0]
    f_out = open(filename_output, 'w')

    # Split components
    cmp_list = f_in.read().split('BeginCmp\n')

    cmp_table = []
    for component in cmp_list:
        # Extract component reference and value
        reference, value, footprint = cmp_extract_info(component)
        if(reference != '' and value != ''):
            cmp_table.append([reference, value, footprint])

    cmp_table = rearrange_table(cmp_table)
    f_out.write('Reference,Value,Quantity,Kicad Footprint,URL\n')
    for component in cmp_table:
        description = '%s,%s,%s,%s,\n' \
                      % (component[0],component[1],component[3],component[2])
        f_out.write(description)

if __name__ == "__main__":
    main()
