#!/usr/bin/env python
# -*- mode: python -*-
# PYTHON_ARGCOMPLETE_OK

import argparse, os, time, sys
import smstools

term = smstools.term
parser = argparse.ArgumentParser(description='Import texts to android sms database file.')
parser.add_argument('infiles', nargs='+', type=str, help='input files, may include multiple sources')
parser.add_argument('outfile', type=str, help='output file to write to.')
parser.add_argument('--type', type=str, help='output type', choices=smstools.OUTPUT_TYPE_CHOICES.keys())
parser.add_argument('-V', '--version', action='version', version="%(prog)s "+smstools.getVersion())

try:
    import argcomplete
    argcomplete.autocomplete(parser)
except:
    pass

args = parser.parse_args()

try:

    ## Check arguments ##

    for filepath in args.infiles:
        if not os.path.exists(filepath) or os.path.getsize(filepath) < 1:
            raise smstools.ArgumentError("%s doesn't exist or has no data" % filepath)
    if os.path.exists(args.outfile):
        raise smstools.ArgumentError("output file [%s] can't exist" % args.outfile)

    outtype = args.type
    if outtype:
        outtype = smstools.OUTPUT_TYPE_CHOICES[outtype]
    else:
        extension = os.path.splitext(args.outfile)[1]
        if extension in smstools.EXTENTION_TYPE_DEFAULTS:
            outtype = smstools.OUTPUT_TYPE_CHOICES[smstools.EXTENTION_TYPE_DEFAULTS[extension]]
        else:
            raise smstools.SMSToolError("unknown output format (use --type argument)")


    ## get the texts into memory ##
    texts = []
    for filename in args.infiles:
        starttime = time.time() #meause execution time
        parser = smstools.getParser(filename)
        new_texts = parser.parse(filename)
        for txt in new_texts:
            if (txt.num == None) or (txt.num == "") or (len(txt.num) < 1):
                smstools.warning("REMOVING text with no number: %s (from %s)" % (txt, os.path.basename(filename)))
                new_texts.remove(txt)
        print term.black_on_blue("%d messages read in %d seconds from %s using parser %s") % \
            (len(new_texts), (time.time()-starttime), os.path.basename(filename), parser.__class__)

        if len(new_texts):
            print "  latest text: " + term.blue(new_texts[-1].localStringTime()) + " to " + term.blue(new_texts[-1].num) + ":"
            print "   " + term.blue(smstools.truncate(new_texts[-1].body))
        texts.extend(new_texts)

    print term.black_on_yellow("sorting all %d texts by date") % len(texts)
    texts = sorted(texts, key=lambda text: text.date)

    outtype().write(texts, args.outfile)
    print term.black_on_yellow("saved messages to %s") % os.path.basename(args.outfile)
except smstools.SMSToolError as e:
    sys.exit(e) #exit with error without traceback
except KeyboardInterrupt:
    sys.exit("\n .. death.. so soon?")
# other exceptions have full traceback
