# This script generates the BOM for the assembly company, based on the pick and place data

import argparse
parser = argparse.ArgumentParser(description='Generates the BOM for the assembly company, based on the pick and place data.')
parser.add_argument('Input_CSV',
					help='Input file name (e.i.:jfex-U1_RX, jfex-U1_RX-PMA or jfex-Tx) on csv format.\
					Make sure the original file has NO "," in the text, as this could cause problems once opening the output BOM with excel.\
					!!!IMPORTANT!!! The header of this file should include REFDES , COMP_CODE, COMP_VALUE,  COMP_MAN, COMP_MAN_NR, SYM_NAME , COMP_ID.')
parser.add_argument('Output_CSV',
					help='Output.csv file name')
args = parser.parse_args()

#inputfile=args.Input_CSV
outputfile=args.Output_CSV

import csv
with open(args.Input_CSV, mode='r')as PandP_csv: # Opening and reading the mapping from a csv
	PandP = csv.DictReader(PandP_csv)
	concatenate=[]
	refdes=[]
	comp_code=[]
	comp_value=[]
	comp_man=[]
	comp_man_nr=[]
	sym_name=[]
	comp_id=[]
	for lines in PandP: 
		refdes.append(lines['REFDES'])
		comp_code.append(lines['COMP_CODE'])
		comp_value.append(lines['COMP_VALUE'])
		comp_man.append(lines['COMP_MAN'])
		comp_man_nr.append(lines['COMP_MAN_NR'])
		sym_name.append(lines['SYM_NAME'])
		comp_id.append(lines['COMP_ID'])
		
		
		concatenate.append(lines['COMP_CODE']+'_'+lines['COMP_VALUE']+'_'+lines['COMP_MAN']+'_'+lines['COMP_MAN_NR']+'_'+lines['SYM_NAME']+'_'+lines['COMP_ID'])
with open(outputfile, 'w', newline='') as f:
	header = ['COMP_CODE','COMP_VALUE','COMP_MAN','COMP_MAN_NR','SYM_NAME','COMP_ID','COUNT','REF']
	writer = csv.writer(f, delimiter=',')
	writer.writerow(header)
	for set_i in set(concatenate): #loop on the set generated by concatenate
		refdes_csv = [refdes[index] for index, value in enumerate(concatenate) if value == set_i]
		for index, value in enumerate(concatenate):
			if value == set_i:
				full_data = [comp_code[index]+','+comp_value[index]+','+comp_man[index]+','+comp_man_nr[index]+','+sym_name[index]+','+comp_id[index]+','+str(len(refdes_csv))+',']
				break
		full_data_csv = (full_data+refdes_csv)
		writer = csv.writer(f, delimiter=',')
		writer.writerow(full_data_csv)