#!/usr/bin/env python2.7

import os
import time
import difflib
from datetime import datetime

import click

CONFIG_CONTENTS = """

##########################################
#
#   Update These Parameters 
#
##########################################

# Name this paper
paper_name = "%s"

# A function that returns shell commands for compiling the latex doc and 
# copying it to the destination location
def make_cmds(dstpath):
  '''
  @param dstpath Where the generated latex file should be moved to
  @return a list of shell commands to run to generate the latex file and move it to dstpath
  '''
  cmds = [
    "cd %s",
    "latexrun main",
    "cp latex.out/main.pdf %%s" %% dstpath
  ]
  return cmds


##########################################
#    Optional
##########################################

# minimum edit distance of tex files to take a snapshot
min_edit_distance = 4000

# Don't create a snapshot if the previous one was within X hours of this commit
min_hours_gap = 12

# where to store the data, no need to change this
dburi = "sqlite:///latex2.db"



##########################################
#    Autogenerated
##########################################

# absolute path to the git_repo
# Make sure things are committed!  
# We will need to checkout many commit points as part of the rollback procedure.
git_repo = "%s"

# the latex document directory (within the git repo)
latex_dir = "%s"

"""

def initialize():
  if os.path.exists("./config.py"): 
    print "found config file"
    return

  papername, cur_dir, git_dir, latex_dir = infer_dirs()
  contents = CONFIG_CONTENTS % (papername, cur_dir, git_dir, latex_dir)

  print "initializing config.py"
  with file("./config.py", "w") as out:
    out.write(contents)

def infer_dirs():
  cur_dir = os.path.abspath(".")
  basename = os.path.basename(cur_dir)

  git_dir = cur_dir
  while git_dir:
    if os.path.exists(os.path.join(git_dir, ".git")):
      break
    git_dir = os.path.dirname(git_dir)

  if not git_dir:
    raise Error("Could not find .git directory in any parent directory.  Are you in a git repo?")

  latex_dir = cur_dir[len(git_dir):]
  return basename, cur_dir, git_dir, latex_dir



if __name__ == '__main__':

  @click.command()
  @click.argument("cmd", nargs=1)
  @click.option("-h", type=int, default=350, help="screenshot height")
  @click.option("-o", help="output directory for exporting")
  @click.option("--port", type=int, default=8000, help="webserver port")
  def main(cmd, h, o, port):
    """
    Commands:

      \b
      init       -- initialize configuration file config.py  Edit this file 
      screenshot -- regenerate screenshots
      latex      -- run latex and generate pdfs
      server     -- run webserver for nice UI
      export     -- export into a folder for static deployment

    Note: this executable loads config.py for the configuration parameters
    """

    if cmd == "init":
      initialize()
      print "Please edit config.py in your current directory"
      print "Then run \"latexsnapshots latex\""
      exit()

    if not os.path.exists("config.py"):
      print "cd to your latex directory and run \"latexsnapshots init\" "
      exit()

    from latexsnapshots.server import run_server
    from latexsnapshots.util import proc_latex, all_screenshots, PDFROOT
    from latexsnapshots.export import export

    if cmd == "screenshot":
      all_screenshots(PDFROOT, h=h)
    elif cmd == "latex":
      proc_latex(h=h)
    elif cmd == 'server':
      run_server('localhost', port)
    elif cmd == "export":
      if o and o != "":
        export(o)
      else:
        print "specify an output directory using -o"


  main()
