#!/usr/bin/python
import os
import sys
import re
import fileinput
import argparse

tzs = [ 0, 0 ]
names = [ "", "" ]

def prnl(out, str):
  out.write("%s%s" % (str, os.linesep))

def gather(inf, index):

    while True:
        l = inf.readline()
        if not l:
            break
        if l[0] == '/' and l[1] == '/':
            continue
        m = re.search(r'"(.*)"', l)
        if m:
            s = re.search(r'(.*);(.*)', m.group(1))
            tzs.append(s.group(2))
            names.append(s.group(1))
        index += 1
    return index

def dec2(n):
  if n < 10:
    return "0%s" % (n)
  return "%s" % (n)

def finish(outf, tmpl, page):

  if outf != None:
    prnl(outf, "")
    prnl(outf, "]")
    outf.close();
  if page >= 0:
    outf = open(tmpl % (dec2(page)), 'w')
    prnl(outf, "[");
  return outf

def out_files(tmpl, len):

  outf = None
  page = -1
  idx = 4
  for i in range(len):
    if idx >= 4:
      page += 1
      outf = finish(outf, tmpl, page)
      pre = ""
      idx = -1
    outf.write('%s  {"tz":%s, "name":"%s"}' % (pre, tzs[i], names[i]))
    idx += 1
    pre = "," + os.linesep
  if idx <= 4:
    finish(outf, tmpl, -1)
  outf = open(tmpl % ("max"), 'w')
  prnl(outf, "export const max = %s;" % (len))
  outf.close()
  return

parser = argparse.ArgumentParser()
parser.add_argument("city_file", help = "Raw city timezone info")
parser.add_argument("country_file", help = "Raw country timezone info")
parser.add_argument("out_tmpl", help = "Outlet files template")
args = parser.parse_args()

idx = gather(open(args.city_file, 'r'), 2)
idx = gather(open(args.country_file, 'r'), idx)

out_files(args.out_tmpl, idx)
