#!/usr/bin/env python3

import sys
import argparse
import os
from os.path import join
from shutil import copyfile

from diffenv.main import *
from diffenv import 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='*', default=None, help='display diff between two environments')
parser.add_argument('--add-hooks', action='store_true', help='install diffenv git hooks in current repo')

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(git_toplevel(), '.git', 'hooks', 'post-commit')
  dirname, filename = os.path.split(os.path.abspath(__file__))
  hooks_src = join(dirname, 'hooks', 'post-commit')
  copyfile(hooks_src, hooks_dst)
  print ("virtualenv: Installed post-commit hook to %s", hooks_dst)

if args.compare is None:
  # Output our results
  print(collect_env(), file=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 = []
    with open(args.compare[0]) as other_file:
      files.append(other_file.readlines())
    if len(args.compare) == 1:
      files = [[l + '\n' for l in collect_env().splitlines()]] + files
    else:
      with open(args.compare[1]) as other_file:
        files.append(other_file.readlines())

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