#import rlcompleter
import gnureadline as readline

import argparse
import re
import sys
import slugify
import tokenize
import colored
import glob
import shutil
import codecs

TEMPLATE =\
"""
NSLocalizedStringWithDefaultValue(@"{slug}",
  {table}, {bundle},
  @"{value}",
  @"{comment}"
)"""

DEFAULT_AUTOREPLACE_PREFIX = "__LOCALIZE"
DEFAULT_SLUG_FORMATTING_ARGUMENT_REPLACE = "[]"
DEFAULT_LOCALIZATIONSTABLE = "kDefaultLocalizationsTable"
DEFAULT_BUNDLE = "kClassBundle"

slugify.ALLOWED_CHARS_PATTERN = re.compile(r'[^-a-z0-9[]]+')

def context_buf_readlines(infile, A=10, B=6):
   prebuf = []
   postbuf = []
   linenum = 0
   for line in infile.readlines():
      postbuf.append(line)
      if len(postbuf) < B:
         continue

      yield prebuf, postbuf[0], postbuf[1:], linenum
      linenum += 1   
      prebuf = prebuf[-A:] + postbuf[0:1]
      postbuf = postbuf[1:]

   for line in postbuf:
      yield prebuf, postbuf[0], postbuf[1:], linenum
      linenum += 1
      prebuf = prebuf[-A:] + postbuf[0:1]
      postbuf = postbuf[1:]

class NoMatchException(Exception):
   pass

class ReplaceAction(Exception):
   pass

default_config = dict(table = DEFAULT_LOCALIZATIONSTABLE,
                      bundle = DEFAULT_BUNDLE,
                      autoreplace_prefix = DEFAULT_AUTOREPLACE_PREFIX,
                      ask_all = False,
                      comments = False)

def parse(filename, infile, outfile, 
          ask_all = False,
          comments = False,
          table = DEFAULT_LOCALIZATIONSTABLE,
          bundle = DEFAULT_BUNDLE,
          autoreplace_prefix = DEFAULT_AUTOREPLACE_PREFIX):

   interactive = ask_all or comments
      
   string_re = re.compile(r'(.*?)@"([^"]+)"(.*)')
   prefix_re = re.compile(r"NSLocalized[a-zA-Z]String\(");
   fmt_re = re.compile(r"%[-0-9\.]*[l]?[difes\@]")

   def slug_from_string(sel):
      items = fmt_re.split(sel)
      newitems = map(lambda item:slugify.slugify(item), items)

      delimiter = "-"+DEFAULT_SLUG_FORMATTING_ARGUMENT_REPLACE +"-"
      slug =  delimiter.join(filter(lambda x:len(x), newitems))
      return slug
   

   w = sys.stdout.write
   fg = colored.fg
   attr = colored.attr

   quit_after = False
   linenum = 0

   replace_autoprefix = True
   
   #for line in infile.readlines():
   for prebuf, line, postbuf, linenum in context_buf_readlines(infile):

      try:
                  
         match =  string_re.match(line)
      
         if not match:
            raise NoMatchException
         
         prefix = match.group(1)
         sel = match.group(2)
         postfix = match.group(3)

         def _print_preamble():