import re

COMMON_LOG_FORMAT = '%h %l %u %t "%r" %s %b'
COMBINED_LOG_FORMAT = '%h %l %u %t "%r" %s %b "%{Referer}i" "%{User-agent}i"'

formatPatt = re.compile('%({(?P<field>[^{]+)})?(?P<key>[a-zA-Z%])')
formatReplaces = {'b' : 'bytes-sent',
                  'f' : 'filename',
                  'a' : 'remote-ip',
                  'h' : 'remote-host',
                  'l' : 'remote-user',
                  'P' : 'pid',
                  'p' : 'server-port',
                  'r' : 'request-line',
                  's' : 'status',
                  't' : 'time',
                  'U' : 'url',
                  'u' : 'username',
                  'v' : 'virtual-host',
                  }

def MakeFormatString(logFormat):
    fields = {'e' : [],
              'i' : [],
              'o' : [],
              }

    def repl(match, fields=fields):
        key = match.group('key')
        if key in formatReplaces.keys():
            return '%%(%s)s' % formatReplaces[key]
        if key in fields.keys():
            name = '%s%d' % (key, len(fields[key]))
            fields[key].append(match.group('field'))
            return '%%(%s)s' % name
        raise SystemExit('Unknown format specifier %s in LogFormat' % match.string)

    format = re.sub(formatPatt, repl, logFormat)
    if format[-1] != '\n':
        format = format + '\n'
    return (format, fields)
