#!python

import sys
import argparse
import os
from os.path import join
from shutil import copyfile, copystat
import requests
from io import StringIO

from diffenv import main, diffviewer

# Handle arguments

parser = argparse.ArgumentParser(
    description='Diff total development environment.')
parser.add_argument('-o', '--output', help='output to file instead of stdout')
parser.add_argument(
    '-c',
    '--compare',
    nargs='*',
    help='display diff between two environments')
parser.add_argument(
    '--add-hooks',
    action='store_true',
    help='install diffenv git hooks in current repo')
parser.add_argument(
    '--share',
    nargs='?',
    const='https://transfer.sh',
    help='Share as POST with provided URL')

args = parser.parse_args()

# Handle outputting to file or stdout
outfilestream = sys.stdout if args.output is None else open(args.output, 'w')

if args.add_hooks:
    # Install git hooks
    hooks_dst = join(main.git_toplevel(), '.git', 'hooks', 'post-commit')
    dirname = os.path.split(os.path.abspath(__file__))[0]
    # Find hooks dir relative to this file
    hooks_src = join(dirname, '..', 'hooks', 'post-commit')
    # Copy the hook
    copyfile(hooks_src, hooks_dst)
    # Make executable
    copystat(hooks_src, hooks_dst)
    print("virtualenv: Installed git post-commit hook to %s" % hooks_dst)
elif args.compare is None:
    env = main.collect_env()
    if args.share is not None:
        buf = StringIO()
        yaml.dump(env, buf)

        upload_url = args.share
        r = requests.post(upload_url, files={'diff': buf.getvalue()})
        print('Run the following line on comparison environment:')
        print()
        print('diffenv --compare ' + r.text)
        print()
    else:
        # Output our results
        main.yaml.dump(env, outfilestream)

else:
    if len(args.compare) == 0:
        # TODO compare to current state to most recent commit
        print("Git hook integration not implemented yet")
    else:
        files = [main.read_file_or_url(name) for name in args.compare]
        if len(files) == 1:
            files = [main.collect_env()] + files

        diffviewer.display_diff(files[0],
                                files[1],
                                outfilestream)
