#!/usr/bin/python3
# Author: Bandie Canis
# License: BSD-2-clause

import xml.etree.ElementTree as ET
import getopt, sys
import os.path

def main(argv):

    infile = ''
    outfile = ''

    try:
        opts, args = getopt.getopt(argv, "hi:o:", ["if=","of="])
    except getopt.GetoptError as err:
        print(err)
        helpMsg(sys.argv[0])
        sys.exit(1)

    for opt, arg in opts:
        if opt == '-h':
            helpMsg(sys.argv[0])
            sys.exit(0)
        elif opt in ('-i', '--if'):
            infile = arg
        elif opt in ('-o', '--of'):
            outfile = arg

    if(infile == '' or outfile == ''):
        helpMsg(sys.argv[0])
        sys.exit(1)

    if not(os.path.isfile(infile)):
        print("Error: ", infile, "doesn't exist.")
        sys.exit(1)
   
    
    doEet(infile, outfile)


def doEet(infile, outfile):


    root = ET.parse(infile).getroot().find('entries')


    f = open(outfile, 'w')
    counter = 0
    for c in root.findall('entry'):
        counter+=1
        tel = c.find('extension').text
        name = c.find('name').text
#        loc = c.find('location').text

        entry = "BEGIN:vCard\nVERSION:3.0\nN:{}\nTEL;type=voice:{}\nCATEGORIES:micropoc\nEND:vCard\n\n".format(name, tel)

        f.write(entry)
    
    f.close()
    print("Contacts processed:", counter)
    print("Have fun! :)")




def helpMsg(progname):
    print(progname, "-i <inputfile.xml> -o <outputfile.vcf>")



if __name__ == "__main__":
   main(sys.argv[1:])
