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

import defaults
import modules
import cgi
import utils
import data
import re
from database import *
import l10n

_ = l10n.gettext

form = cgi.FieldStorage()

def check(**fields):
    for field in fields:
        if field in form:
            value = form[field].value
        if re.search(fields[field], value, re.U):
            return 1
        else:
            return 0

def pogrep(posource, searchstring, cmdlineoptions=None):
    """
    Search for a string in a PO file
    """
    from translate.storage import po
    from translate.tools import pogrep
    if cmdlineoptions is None:
        cmdlineoptions = []
    options, args = pogrep.cmdlineparser().parse_args(["xxx.po"] + \
                                                      cmdlineoptions)
    grepfilter = pogrep.pogrepfilter(searchstring, options.searchparts,
                                     options.ignorecase, options.useregexp,
                                     options.invertmatch, options.accelchar)
    tofile = grepfilter.filterfile(po.pofile(posource))
    return str(tofile)

if __name__ == "__main__":
    import os
    import cgitb; cgitb.enable()
    import commands
    from operator import itemgetter
    from Cheetah.Template import Template
    from teams import TranslationLanguages
    
    l10n.set_language()
    print "Content-type: text/html; charset=UTF-8\n"
    html = Template(file="templates/search.tmpl", filter=l10n.MyFilter)
    html._ = l10n.gettext
    html.rtl = (defaults.language in defaults.rtl_languages)
    html.languages = sorted(TranslationLanguages().iteritems(), key=itemgetter(1))

    if 's' in form:
        found_errors = False
        # FIXME: This doesn't quite avoid escaping etc.
        #if not check(s=u'^\w+$'):
        #    html.msg = _("The value you have entered is not valid."
        #                 " Please try again.")
        #    found_errors = True
        searchstring = form['s'].value.decode('utf8')
        if len(searchstring) < 2:
            html.msg = _("Search string must be 2 letters or more.")
            found_errors = True
            
        sections = {'msgid': 'K',
                    'msgstr': 'T',}
        sects2search = []
        for (s,o) in sections.items():
            if form.has_key(s):
                sects2search.append(o)
        if not len(sects2search):
            html.msg = _("You must choose at least one section.")
            found_errors = True   
                
        if not found_errors:
            modules = modules.XmlModules(defaults.modules_xml)
            ret = {}
            #FIXME: Make this not so nested
            for (id, m) in modules.items():
                localroot = os.path.join(defaults.scratchdir,
                                         m["scmroot"]["type"])
                branches = m["branch"]
                for (id, b) in branches.items():
                    branch = b["id"]
                    for podir in m["branch"][branch]["domain"]:
                        potbase = m["branch"][branch]["domain"][podir]['potbase']
                        outputdir = os.path.join(defaults.potdir,
                                                 m["id"] + "." + branch)
                        outputdomain = potbase + "." + branch
                        language = form['language'].value
                        if language == "POT":
                            langdomain = "%s.pot" % (outputdomain)
                        else:
                            langdomain = "%s.%s.po" % (outputdomain,
                                                       language)
                        langtarget = os.path.join(outputdir,
                                                  langdomain)
                        if os.access(outputdir, os.X_OK) and \
                           os.access(langtarget, os.R_OK):
                            options = []
                            if form.has_key('ignore-case'):
                                options.append("--ignore-case")
                            # Regular expressions
                            if form.has_key('regex'):
                                pattern = ''
                            else:
                                pattern = ' -F'
                            searchthis = ' '.join(["-%s%s -e '%s'" % (
                                                  s,
                                                  pattern,
                                                  searchstring.encode('utf8'))
                                                 for s in sects2search])
                            command = "msggrep %(str)s %(opts)s %(file)s" % {
                                       'opts': ' '.join(options),
                                       'str': searchthis,
                                       'file': langtarget.encode('utf8')}
                            # to fix charset errors:
                            # command = "export LC_ALL=en_US.UTF-8 && " + command
                            (error, output) = commands.getstatusoutput(command)
                            if output and not error:
                                results = output
                                from cgi import escape
                                #escape < > &
                                results = escape(results)
                                # % causes us problems 'cause python thinks
                                # it's a replacement character
                                results = results.replace('%', '%%')
                                if form.has_key('highlight'):
                                    searchthis = '(%s)' % searchstring
                                    p = re.compile(searchthis,
                                                   re.UNICODE | re.IGNORECASE)
                                    results = p.sub(r'<span class="highlight">\1</span>',
                                                    results.decode('utf8'))
                                ret.update({langdomain: results})

            html.ret = sorted(ret.iteritems())
            html.searchstring = searchstring

    print unicode(html).encode('utf-8')
    print utils.TemplateInspector(html)
