#!/usr/bin/env python3
from __future__ import print_function
import Mesh3D
import os

def test_and_fix_target(errorfnc,fn):
    import os
    fn=os.path.abspath(os.path.realpath(os.path.expanduser(fn)))
    if os.path.exists(fn):
        errorfnc('Target file %s already exists'%os.path.relpath(fn))
    if not fn.endswith('.mesh3d'):
        fn+='.mesh3d'
    if not os.path.isdir(os.path.dirname(fn)):
        errorfnc('Target directory %s does not exist'%os.path.relpath(os.path.dirname(fn)))
    return fn

def parse_cmd_line():
    import argparse as AP
    parser = AP.ArgumentParser(description='Merge contents of two or more .mesh3d files'
                               +' into a new one. Note that the metadata of the files'
                               +' must be exactly similar or the merging will fail.',
                               usage='%(prog)s [-h] [-d] -o TARGET <SRCFILES>')

    parser.add_argument('srcfiles', metavar='SRCFILES', type=str, nargs='+',
                        help='Two or more .mesh3d files to merge (wildcards allowed)')
    parser.add_argument('-o',dest='target', metavar='TARGET', type=str,
                        help='destination file',required=True)#ARGH, fixme, why does it show up in
                                                              #the "optional" section of --help?

    args=parser.parse_args()

    #for convenience, expand any input file with '*', '[' or '?' in it via glob,
    #and always expanduser:
    tmp=[]
    for sfraw in args.srcfiles:
        sf=os.path.expanduser(sfraw)
        if '*' in sf or '[' in sf or '?' in sf:
            import glob
            sf=glob.glob(sf)
            if not sf:
                parser.error('No files selected by pattern "%s"'%sfraw)
            tmp+=sf
        else:
            if not os.path.exists(sf):
                parser.error('Input file not found: %s'%sf)
            tmp+=[sf]
    args.srcfiles=tmp

    if len(args.srcfiles)<2:
        parser.error('Please provide at least 2 input files')

    #Guard against multiple:
    srcabs=[os.path.abspath(os.path.realpath(s)) for s in args.srcfiles]
    if len(set(srcabs))!=len(args.srcfiles):
        parser.error('Multiple identical input files specified')
    args.srcfiles=srcabs

    args.target=test_and_fix_target(parser.error,args.target)

    return args

args=parse_cmd_line()

print("Merging %i files"%len(args.srcfiles))
Mesh3D.merge_files(args.target,args.srcfiles)
print("Merging OK")

