# coding: utf-8

import ru.curs.celesta.Celesta as Celesta
import ru.curs.celesta.ConnectionPool as ConnectionPool
import ru.curs.celesta.CallContext as CallContext
import ru.curs.celesta.SessionContext as SessionContext
import sys

# 1. При запуске из Eclipse надо обеспечить, чтобы первый вызов,
# инициализирующий Celesta, был бы именно getDebugInstane(), а не getInstance()

Celesta.getDebugInstance()
conn = ConnectionPool.get()
sesContext = SessionContext('super', 'testsession')
context = CallContext(conn, sesContext)

# 2. Этот блок должен идти до выражений import, импортирующих отлаживаемые гранулы!!
sys.modules['initcontext'] = lambda: context


import os

from common.sysfunctions import tableCursorImport
from common.dbutils import DataBaseXMLExchange
from java.io import FileOutputStream

def exportData(tableInstance, path):
    dataStream = FileOutputStream(path)
    exchange = DataBaseXMLExchange(dataStream, tableInstance)
    exchange.downloadXML()
    dataStream.close()

def exportTables(context):
    filePath = os.path.dirname(os.path.abspath(__file__))

    exportTables = [{'grain': 'celesta', 'table': 'Roles'},
                    {'grain': 'celesta', 'table': 'Permissions'},

                    {'grain': 'common', 'table': 'numbersSeries'},
                    {'grain': 'common', 'table': 'linesOfNumbersSeries'},

                    {'grain': 'security', 'table': 'customPermsTypes'},
                    {'grain': 'security', 'table': 'customPerms'},
                    {'grain': 'security', 'table': 'rolesCustomPerms'},

                    {'grain': 'nci', 'table': 'control_form_type'},
                    {'grain': 'nci', 'table': 'cprogram_attr_list'},
                    {'grain': 'nci', 'table': 'education_form'},
                    {'grain': 'nci', 'table': 'edu_event_type'},
                    {'grain': 'nci', 'table': 'education_level'},
                    {'grain': 'nci', 'table': 'staff_scale'},
                    {'grain': 'nci', 'table': 'staff_area'},
                    {'grain': 'nci', 'table': 'status_model'},
                    {'grain': 'nci', 'table': 'status_list'},
                    {'grain': 'nci', 'table': 'status_model_status'},
                    # ПОДУМАТЬ как организовать загрузку
                    # {'grain': 'nci', 'table': 'edu_organization'}
                    # {'grain': 'nci', 'table': 'speciality'},
                    ]

    for table in exportTables:
        tableInstance = tableCursorImport(table['grain'], table['table'])(context)
        exportData(tableInstance, filePath + '/' + table['table'] + '.xml')

exportTables(context)