# coding=utf-8

# индивидуальные настройки проекта, изменяемые разработчиком решений
################################
settings = {
        # путь к папкам с гранулами (score)
        "score.path": [r"/celesta/certif/trunk/default/score",
                       r"/celesta/certif/trunk/common.sys/score",
                       r"/celesta/certif/trunk/admin/score",
                       r"/celesta/certif/trunk/common.accred/score",
                       r"/celesta/certif/trunk/edu/score",
                       r"/celesta/certif/trunk/medstaff/score",
                       r"/celesta/certif/trunk/method/score"
                       ],
        # путь к питон библиотеками
        "pylib.path": r"\\celesta\\pylib",
        # путь к файлу с настройками гранул
        "grainssettings.path": r"\\celesta\\certif\\trunk\\grainsSettings.xml",
        # драйвер базы данных
        "database.classname": r"org.postgresql.Driver",
        # строка подключения к базе данных
        "database.connection": r"jdbc:postgresql://localhost:5432/accred?user=postgres&password=F708420Dx"
        }

################################
# далее код, не требующий изменений от разработчика решений
import xml.etree.ElementTree as ET
import codecs
import os

pathList = os.path.abspath(__file__).split('\\')
pathRoot = r'\\'.join(pathList[:pathList.index('celesta')])
pathRootCelesta = r'%s\\celesta' % pathRoot
PYDEVPROJECT_FILE = '%s\\.pydevproject' % pathRootCelesta
CELSTAPROPERTIES_FILE = ('%s\\celesta.properties' % pathRootCelesta, '%s\\build\\celesta.properties' % pathRootCelesta)

# обновление настроек Python
tree = ET.parse(PYDEVPROJECT_FILE)
root = tree.getroot()
removeList = list()
for pydev in root:
    if pydev.tag == "pydev_pathproperty" and pydev.attrib['name'] == 'org.python.pydev.PROJECT_SOURCE_PATH':
        for path in pydev:
            if path.text[-5:] == 'score' :
                removeList.append(path)
        for tag in removeList:
            pydev.remove(tag)
        for newPath in settings["score.path"]:
            newPathElement = ET.SubElement(pydev, 'path')
            newPathElement.text = newPath
    elif pydev.tag == "pydev_property" and pydev.attrib['name'] == 'org.python.pydev.PYTHON_PROJECT_INTERPRETER' and "pyInterpreter" in settings and settings['pyInterpreter']:
        pydev.text = settings['pyInterpreter']
    elif pydev.tag == "pydev_property" and pydev.attrib['name'] == 'org.python.pydev.PYTHON_PROJECT_VERSION' and "pyVersion" in settings and settings['pyVersion']:
        pydev.text = 'jython %s' % settings['pyVersion']



outfile = codecs.open(PYDEVPROJECT_FILE, 'w', encoding='utf-8')
outfile.write('''<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<?eclipse-pydev version="1.0"?>''')
tree.write(outfile)
outfile.close()
# Обновление настроек celesta.properties
for settingsFile in CELSTAPROPERTIES_FILE:
    outfile = codecs.open(settingsFile, 'w', encoding='utf-8')
    for prop in settings:
        if prop == "score.path":
            scorePath = []
            for score in settings[prop]:
                scorePath.append('%s%s' % (pathRoot, score))
            outfile.write(u'%s=%s\n' % (prop, ';'.join(scorePath)))
        elif prop in ("pylib.path", "grainssettings.path"):
            outfile.write(u'%s=%s\n' % (prop, '%s%s' % (pathRoot, settings[prop])))
        elif prop in ("database.classname", "database.connection"):
            outfile.write(u'%s=%s\n' % (prop, settings[prop]))
    outfile.close()