import subprocess
import tempfile
import os.path
from settings import PAGEDJS_BINARY_PATH


basepath = os.path.abspath(os.path.dirname(__file__))

def run_pagedjs (path_html, path_pdf, cwd=None, extra_scripts=[]):
  args = [
    PAGEDJS_BINARY_PATH
  ]

  for script in extra_scripts:
    args.extend([
      '--additional-script',
      script
    ])

  args.extend([
    '-o', path_pdf,
    path_html
  ])

  try:
    return subprocess.check_output(args, cwd=cwd, stderr=subprocess.STDOUT).decode()
  except subprocess.CalledProcessError as e:
    return 'Error:\n{}'.format(e.output.decode())

"""
  Generate a PDF based on provided HTML using pagedjs and returns the contents of
  the generated PDF.

  If optional path_out is provided the PDF is written there and the function returns the path.
  
  Optional extra_scripts is a list of strings with javascript.
  Scripts are sent in the same order to paged.js
"""
def make_pdf (html, path_out=None, extra_scripts=[]):
  with tempfile.TemporaryDirectory(prefix='algoliterary_publishing_house_') as tempdir:
    with tempfile.NamedTemporaryFile(dir=tempdir, mode='w', suffix='.html', delete=False) as temphtml:
      # Store html in a temporary file  
      temphtml.write(html)
      temphtml.close()

      name_in = temphtml.name

      extra_scripts_tmp = []

      for script in extra_scripts:
        with tempfile.NamedTemporaryFile(dir=tempdir, mode='w', suffix='.js', delete=False) as tempjs:
          tempjs.write(script)
          tempjs.close()
          extra_scripts_tmp.append(tempjs.name)

      # Make a temporary file for the generated PDF
      with tempfile.NamedTemporaryFile(dir=tempdir, mode='w', suffix='.pdf', delete=False) as temppdf:
        temppdf.close()
        name_out = temppdf.name

        # Make the pdf
        run_pagedjs(name_in, name_out, cwd=basepath, extra_scripts=extra_scripts_tmp)

        if path_out:
          import shutil
          shutil.copy(name_out, path_out)
          return path_out
        else:
          with open(name_out, 'rb') as generated_pdf:
            return generated_pdf.read()

if __name__ == '__main__':


  with open(os.path.join(basepath, 'index.html'), 'r') as file_input:
    html = file_input.read()

    with open(os.path.join(basepath, 'delayedLoading.js'), 'r') as js_input:
      js = js_input.read()
    
      make_pdf(html, os.path.join(basepath, 'generated.pdf'), [ js ])
    
      