#!/usr/bin/env python
# -*- coding: utf-8 -*-

'''Ensures the editor JS code is available during tests'''

import os
import sys
import glob

key = '%%jsfiles%%'
scriptdir = os.path.realpath(os.path.dirname(sys.argv[0]))

try:
  import pkg_resources
  import beat.editorx
  jsfiles = pkg_resources.resource_filename(beat.editor.__name__, 'js')
  print('Running test (beat.editor import suceeded) - setting javascript path to %s' % jsfiles)
except ImportError as e:
  jsfiles = os.path.realpath(os.path.join(scriptdir, '..', 'beat', 'editor',
    'js'))
  print('Running build (beat.editor import failed) - setting javascript path to %s' % jsfiles)

if not os.path.exists(jsfiles):
  print('  Creating directory %s' % jsfiles)
  os.makedirs(jsfiles)

templatedir = os.path.realpath(os.path.join(scriptdir, 'js'))
for k in glob.glob(os.path.join(templatedir, '*.template')):
  output = os.path.splitext(k)[0]
  print('  ** Replacing template %s -> %s' % (k, output))
  with open(k, 'rt') as reader, open(output, 'wt') as writer:
    for line in reader:
      if key in line: line = line.replace(key, jsfiles)
      writer.writelines([line])
