#!/usr/bin/python

# Copyright 2013 Chiraag M. Nataraj
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

import sys
import argparse
import datetime

now = datetime.datetime.now()

parser = argparse.ArgumentParser(description="%(prog)s is a small script to convert from the sCard format to formats such as LaTeX and vCard")
parser.add_argument('input', help="File to parse")
parser.add_argument('output', help="File to output to")
parser.add_argument("-s", "--sort", dest="method", metavar="COL", type=int, help="Set column to sort by (starts at 0) [default:%(default)s]", default=0)
parser.add_argument("-S", "--secondary-sort", metavar="COL", dest="method2", type=int, help="Set secondary column to sort by (starts at 0) (necessary to correct for Python's stable sort) [default:%(default)s]", default=1)
parser.add_argument("-f", "--format", dest="format", help="Set the output format. [default:%(default)s]", default="latex", choices=['latex', 'vcard'])
headers = []

def latex(outfile, items):
    for i in range(len(items)):
        for k in range(len(items[i])):
            append = "" if (k == (len(items[i]) - 1)) else " & "
            outfile.write(items[i][k] + append)
        outfile.write(" \\\\")
        outfile.write("\n")

def aliases(outfile, items):
    global headers
    consolidation = {}
    order = {}
    column = 0
    repititions = []
    print(headers)
    for i in range(len(headers)):
        key = headers[i].split("[")[0]
        rep = int(headers[i].split("[")[1][0:1])
        consolidation[key] = range(column, column + rep)
        order[i] = key
        column += rep
        repititions.append(rep)
    if sum(repititions) != len(items[0]):
        print("Error: not enough headers!")
        sys.exit(2)
    if not consolidation.has_key("EMAIL") or not consolidation.has_key("FN"):
        print("Error: must have EMAIL header!")
        sys.exit(3)
    name = consolidation["FN"]
    em = consolidation["EMAIL"]
    towrite = ""
    print(name)
    print(em)
    # for item in items:
    #     towrite += "alias "

def vcard(outfile, items):
    global headers
    consolidation = {}
    order = {}
    column = 0
    repetitions = []
    for i in range(len(headers)):
        key = headers[i].split("[")[0]
        rep = int(headers[i].split("[")[1][0:1])
        consolidation[key] = range(column, column + rep)
        order[i] = key
        column += rep
        repetitions.append(rep)
    if sum(repetitions) != len(items[0]):
        print("Error: not enough headers!")
        sys.exit(2)
    for i in range(len(items)):
        outfile.write("BEGIN:VCARD")
        outfile.write("\n")
        outfile.write("VERSION:2.1")
        outfile.write("\n")
        outfile.write("X-PRODID: MOBILE")
        outfile.write("\n")
        outfile.write("X-CT:PERSON")
        outfile.write("\n")
        towrite = ""
        for index in consolidation:
            nonEmpty = True
            if all([items[i][col] == "" for col in consolidation[index]]):
                print consolidation[index]
                print items[i]
                nonEmpty = False
            if nonEmpty:
                towrite += index + ":"
                if index == "FN":
                    newwrite = "N:"
                    back = len(consolidation[index]) - 1
                    while back > 0:
                        newwrite += items[i][consolidation[index][back]] + ";"
                        back -= 1
                    newwrite += items[i][consolidation[index][0]]
                    newwrite += "\nFN:"
                    towrite = towrite.replace("FN:", newwrite)
                for col in consolidation[index]:
                    string = items[i][col].replace("\\newline ", "\n" + index + ":")
                    towrite += string + " "
                towrite += "\n"
        outfile.write(towrite)
        outfile.write("REV:" + now.strftime("%Y%m%dT%H%M%S0Z") + "\n")
        outfile.write("END:VCARD")
        outfile.write("\n")

def parse_address_book(addressbook, output, method, format):
    global headers
    infile = open(addressbook, 'r')
    rows = []
    while True:
        s = infile.readline()
        if s == '':
            break
        rows.append(s.strip())
    infile.close()
    items = []
    for i in rows:
        items.append(i.split(":"))
    for j in range(len(items)):
        for k in range(len(items[j])):
            items[j][k] = items[j][k].replace('\\n', '\\newline').strip()
            items[j][k] = items[j][k].replace('_', '\\_')
    if(format == "vcard"):
        headers = items.pop(0)
        for i in rows:
            for j in range(len(items)):
                for k in range(len(items[j])):
                    for lang in ["knd","dev","chn","bng","pnj","tlg","guj","tam","mlm","grk","rus"]:
                        items[j][k] = items[j][k].replace('{\\' + lang,'').strip()
                        items[j][k] = items[j][k].replace('}','').strip()
    else:
        items.pop(0)
    # print(headers)
    items = sorted(sorted(items, key=lambda item: item[method[1]]), key=lambda item: item[method[0]])
    # return(items)
    # print items
    outfile = open(output, 'w')
    globals()[format](outfile, items)
    outfile.close()

def main():
    args = parser.parse_args()
    parse_address_book(args.input, args.output, (args.method, args.method2), args.format)

if __name__ == "__main__":
    main()
    # items = parse_address_book("Address_Book/address_book","test", (0,1), vcard)
    # print(items)
    # print(headers)
    # aliases("test", items)
