#!/usr/bin/env python

from __future__ import print_function

import argparse
import json
import os
import sys

import yaml
from jj2c import eprint
import jj2c

AP = argparse.ArgumentParser(
    description='jj2c -- A jinja2 template compiler, version: %s' % jj2c.__VERSION__
)
AP.add_argument('template', help='file pointing to template')
AP.add_argument(
    '-V', '--variables', default=[],
    nargs='+', help='Content or files pointing to variables. Supported formats are: json, yaml and toml.')
AP.add_argument('-o', '--output', default='-', help='where to save the file')
AP.add_argument('-i', '--inspect', action='store_true', default=False, help='Inspect parameters')
AP.add_argument('-e', '--extensions', nargs='+', type=str, default=[], help='Jinja2 extensions')
AP.add_argument('-la', '--lines_as_array', nargs='+', type=str, default=[], help='use line split txt file as an array')


def load_lines_as_array(larg):
  ret = {}
  try:
    fname, fpath = larg.split('=')
  except ValueError:
    eprint('lines_as_array argument has to be a=')
    sys.exit(2)

  with open(fpath) as f:
    ret[fname] = [l2 for l2 in [l.strip() for l in f.readlines()] if l2]
  return ret


def is_tpl(fpath):
  msg = 'No such *FILE*: %s' % fpath
  if os.path.isdir(fpath):
    return False
  if not os.path.isfile(fpath):
    raise Exception(msg)
  return not fpath.endswith('.zip')


def load_variables(fname_or_content):
  ve = jj2c.VariableExtractor(fname_or_content)
  fmt, variables = ve.extract()
  return variables


def dump_file(fpath, content):
  if fpath == '-':
    sys.stdout.write(content)
    sys.stdout.flush()
  else:
    with open(fpath, 'w') as f:
      f.write(content)


def main(args):
  variables = {}

  for file_or_content in args.variables:
    if args.inspect:
      eprint('Parsing variables from: {}'.format(file_or_content))
    x_variables = load_variables(file_or_content)
    if args.inspect:
      eprint(yaml.dump(x_variables))
      eprint('-----\n')
    variables.update(x_variables)

  for l in args.lines_as_array:
    x_variables = load_lines_as_array(l)
    if args.inspect:
      eprint('Parsing variables from: {}'.format(l))
      eprint(yaml.dump(x_variables))
    variables.update(x_variables)

  template_path = args.template
  if template_path.endswith('/'):
    template_path = template_path[:-1]

  if args.extensions:
    eprint(f'Using extensions: {args.extensions}')

  path_info = 'src: {}\ndest:{}'.format(template_path, args.output)

  if os.path.isdir(template_path):
    if args.output.endswith('.zip'):
      eprint('Compiling... tpl(dir) to zip')
      eprint(path_info)
      jj2c.compile_dir_2_zip(
          template_path, args.output, variables, args.extensions)
    else:
      eprint('Compiling... tpl(dir) to dir')
      eprint(path_info)
      jj2c.compile_dir(
          template_path, args.output, variables, args.extensions)
  elif template_path.endswith('.zip'):
    if args.output.endswith('.zip'):
      eprint('Compiling... tpl(zip) to zip')
      eprint(path_info)
      jj2c.compile_zip_2_zip(
          template_path, args.output, variables, args.extensions)
    else:
      eprint('Compiling... tpl(zip) to dir')
      eprint(path_info)
      jj2c.compile_zip_2_dir(
          template_path, args.output, variables, args.extensions)
  elif is_tpl(template_path):
    if args.output == '-':
      eprint('Compiling... file to stdout')
    else:
      eprint(f'Compiling... file to file: {args.output}')
    with open(template_path) as f:
      eprint(path_info)
      dump_file(args.output, jj2c.compile(f.read(), variables, args.extensions))
  else:
    eprint('Path info:', path_info)
    print('Unsupported path')
    sys.exit(1)


if __name__ == '__main__':
  main(AP.parse_args())
