#!/usr/bin/env python

import os
import sys
import fileinput
import re
import fnmatch

srcdir=os.path.join(os.environ['HOME'], 'src/grass_trunk')
#srcdir='/data/tmp/grass71'
infile=os.path.join(srcdir, 'lib/gis/renamed_options')

def get_prefix(module):
    return {
        'd' : 'display',
        'g' : 'general',
        'db' : 'db',
        'i' : 'imagery',
        'r' : 'raster',
        'r3' : 'raster3d',
        'v' : 'vector',
        'm' : 'misc',
    }[module.split('.', 1)[0]]

def fix_html(module, oldkey, newkey):
    if module:
        if module.startswith('v.lrs'):
            html = os.path.join(srcdir, get_prefix(module), 'v.lrs', module, module + '.html')
        elif module.startswith('r.sim'):
            html = os.path.join(srcdir, get_prefix(module), 'r.sim', module, module + '.html')
        elif module.startswith('r.li'):
            html = os.path.join(srcdir, get_prefix(module), 'r.li', module, module + '.html')
        elif module == 'r.watershed':
            html = os.path.join(srcdir, get_prefix(module), module, 'front', module + '.html')
        else:
            html = os.path.join(srcdir, get_prefix(module), module, module + '.html')
            if not os.path.exists(html):
                html = os.path.join(srcdir, 'scripts', module, module + '.html')
        if not os.path.exists(html):
            print >> sys.stderr, "File %s not exists" % html

        modify_html(html, oldkey, newkey)
    else:
        print "TODO: fix_html not module case"

def get_py_list():
    pylist = []
    for root, dirnames, filenames in os.walk(srcdir):
        for filename in fnmatch.filter(filenames, '*.py'):
            pylist.append(os.path.join(root, filename))

    return pylist

def find_sub_string(raw_string, start_marker, end_marker, oldkey, newkey):
    return re.sub(
        r'(?<={}).*?(?={})'.format(re.escape(start_marker), re.escape(end_marker)),
        lambda m: m.group().strip().replace(oldkey, newkey),
        raw_string)

def fix_py(module, oldkey, newkey, files):
    edit = False
    nlines = 0
    for py in files:
        for i, line in enumerate(fileinput.input(py, inplace=1)):
            if not module:
                edit = True
            elif module in line:
                edit = True
                nlines = 0
            if edit and nlines > 10:
                edit = False
            if edit:
                sys.stdout.write(line.replace(oldkey, newkey))
                edit = False
            else:
                sys.stdout.write(line)
            nlines += 1
                
def modify_html(html, oldkey, newkey):
    indiv = False
    for i, line in enumerate(fileinput.input(html, inplace=1)):
        if '<div class' in line:
            indiv = True
        if 'pre></div>' in line:
            indiv = False
        if indiv:
            sys.stdout.write(line.replace(oldkey + '=', newkey + '='))
        else:
            sys.stdout.write(find_sub_string(line, '<b>', '</b>', oldkey, newkey))

def modify_py(pyf, oldkey, newkey):
    for i, line in enumerate(fileinput.input(py, inplace=1)):
        sys.stdout.write(line.replace(oldkey, newkey))
            
def get_changes(infile):
    lines = []
    fd = open(infile)
    for line in fd.readlines():
        line = line.rstrip(os.linesep)
        if line.startswith('#'):
            continue

        key = line.split(':')[0]
        if '|' in key:
            module, oldkey = key.split('|')
        else:
            module = None
            oldkey = key
        newkey = line.split(':')[1]

        lines.append((module, oldkey, newkey))
        
    fd.close()

    return lines
    
if __name__ == "__main__":
    pylist = get_py_list()
    for module, oldkey, newkey in get_changes(infile):
        #fix_html(module, oldkey, newkey)
        #fix_py(module, oldkey, newkey, pylist)
