#!/usr/bin/python3

'''
merge-talkgroups.py - merge 2 ACB Digital Talkgroup files into one.

Usage: merge-talkgroups.py [-868] file1.csv file2.csv

Output will be written to Talkgroups-Merged.csv, errors on stdout/stderr.
-868 add checking for dupliate talkgroup id with different names.
This is not allowed on the CPS for Anytone-868.
'''

import argparse
import collections
import csv
import sys

talkgroups = {}
talkgroup_ids = {}
fieldnames=['name', 'tgid']

def readFile(file, noDupTGIDs):
    global talkgroups

    print('Processing %s' % file)
    with open(file) as csvfile:
        reader = csv.DictReader(csvfile, fieldnames=fieldnames)
        for row in reader:
            #print("%s" % row)
            name = row['name']
            tgid = row['tgid']
            if name in talkgroups:
                if talkgroups[name] != tgid:
                    print('Duplicate name (%s) with different TGID (%s, %s)' % (name, talkgroups[name], tgid))
                    break
            if noDupTGIDs and tgid in talkgroups:
                if talkgroups_ids[tgid] != name:
                    print('Duplicate tgid (%s) with different NAME (%s, %s)' % (tgid, talkgroup_ids[tgid], name))
            talkgroups[row['name']] = tgid
            talkgroup_ids[row['tgid']] = name
    #print("%s" % talkgroups)
    return

def writeFile(outputFile):
    global talkgroups

    with open(outputFile, 'w', newline='') as csvfile:
        writer = csv.DictWriter(csvfile, fieldnames=fieldnames)

        for name in sorted(talkgroups.keys()): 
            writer.writerow({'name': name, 'tgid': talkgroups[name]})
    print('Output written to %s' % outputFile)

def main(argv):
    parser = argparse.ArgumentParser()
    parser.add_argument('-d', '--noDupTGIDs', help='ignore duplicate tgids and print warning', action='store_true', default='store_false')
    parser.add_argument('files', nargs='*', help='list of 2 or more CSV files')
    parser.add_argument('-o', '--output', nargs='?', const='Talkgroups-Merged.csv', help='output filename, default Talkgroups-Merged.csv')
    args = parser.parse_args()

    if len(args.files) < 2:
        print('not enough files')
        parser.print_help()
        quit()

    for file in args.files:
        readFile(file, noDupTGIDs=args.noDupTGIDs)

    writeFile('Talkgroups-Merged.csv')
    
main(sys.argv)
