#!/Users/castro/miniconda2/envs/temp/bin/python

import os
import sys
import shutil
import argparse
from hstools import hydroshare, log

logger = log.logger


def add_file(hs, resid, files):

    return hs.addContentToExistingResource(resid, files)


if __name__ == '__main__':

    desc = """Add files to an existing HydroShare resource
           """
    parser = argparse.ArgumentParser(description=desc)
    parser.add_argument('resource_id', 
                         type=str,
                         help='unique HydroShare resource identifier')
    parser.add_argument('-f', '--files', required=True,
                        type=str, nargs='+',
                        help='files to add to resource')

    # todo: parser force overwrite files?
    parser.add_argument('--overwrite', action='store_true',
                        help='overwrite existing resource files with the same name')
    parser.add_argument('-v', default=True, action='store_true',
                        help='verbose output')
    parser.add_argument('-q', default=False, action='store_true',
                        help='supress output')

    args = parser.parse_args()

    if args.v:
        log.set_verbose()
    if args.q:
        log.set_quiet()

    # make sure input files exist
    for f in args.files:
        if not os.path.exists(f):
            raise Exception(f'Could not find file: {f}')
            sys.exit(1)

    # connect to hydroshare
    hs = hydroshare.hydroshare()
    if hs is None:
        raise Exception(f'Connection to HydroShare failed')
        sys.exit(1)
        
    try:
        response = hs.getResourceFiles(args.resource_id)
        res_files = []
        if len(response) > 0:
            res_files =  [r['file_name'] for r in response]
    except Exception:
        raise Exception('Error connecting to HydroShare resource')

    # make sure files don't already exist
    fnames = [os.path.basename(f) for f in args.files]
    file_conflicts = []
    if len(res_files) > 0:
        for rf in res_files:
            if rf in fnames:
                file_conflicts.append(rf)

    if len(file_conflicts) > 0:
        if not args.overwrite:
            raise Exception('The following file(s) already exist in the resource. Use the --overwrite flag to replace them')
        else:
            for fc in file_conflicts:
                logger.info(f'- removing: {fc}')
                hs.hs.deleteResourceFile(args.resource_id, fc)

    resource_id = add_file(hs, args.resource_id, args.files)

