#!/usr/bin/python
#
# Copyright (c) 2010 Red Hat, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#           http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#

import re
import sys
#I have find a good way to import the generateDS module,
# So I add this module path to sys path, tentatively
sys.path.append("/usr/lib/python2.7/site-packages/generateDS-2.7b-py2.7.egg/EGG-INFO/scripts/")
try:
    import generateDS
except ImportError:
    print "Error: Module generateDS not available."
    exit(1)
from generateDS import *

def findTheLastImportModule(headTemplate):
    # I suppose the code generated by generateDS should import some code. 
    p = re.compile('\nimport\s.*')
    match = p.findall(headTemplate)
    return  match.pop()

def addExtraImportModule(headTemplate, rule, modules=[]): 
    if not modules or not rule:
        return headTemplate
    replace = rule + "\n\n# Begin NOT_GENERATED\n"
    for moudle in modules:
        replace = replace + moudle + "\n" 
    replace = replace + "# End NOT_GENERATED"
    return re.sub(rule, replace, generateDS.TEMPLATE_HEADER, 1)

rule = findTheLastImportModule(generateDS.TEMPLATE_HEADER)

#this modules list can be set in a configure file
modules = ["from ovirtsdk.utils.reflectionhelper import ReflectionHelper"]
generateDS.TEMPLATE_HEADER = addExtraImportModule(
                    generateDS.TEMPLATE_HEADER, rule, modules)
#now, it is ok to add the import module.
print generateDS.TEMPLATE_HEADER

