# coding: utf-8

from java.util import ArrayList
from qt._qt_orm import QtiThemeCursor, QtiQuestionCursor
from ru.curs.celesta.showcase.utils import XMLJSONConverter
import json

try:
    from ru.curs.showcase.core.jython import JythonDTO
    from ru.curs.showcase.core.jython import JythonDownloadResult
    from ru.curs.showcase.core.selector import ResultSelectorData
    from ru.beta2.extra.gwt.ui.selector.api import DataRecord
except:
    from ru.curs.celesta.showcase import JythonDTO

def procListAndCount(context, main=None, add=None, filterinfo=None, session=None, params=None, curValue=None, startsWith=None, firstRecord=None, recordCount=None):

    data = procList(context, main, add, filterinfo, session, params, curValue, startsWith, firstRecord, recordCount)
    count = procCount(context, main, add, filterinfo, session, params, curValue, startsWith)
    return ResultSelectorData(data.getDataRecordList(), count.getCount())

def procList(context, main, add, filterinfo, session, params,
                curvalue, startswith, firstrecord, recordcount):
    u'''Функция list селектора ThemeID'''

    QtiTheme = QtiThemeCursor(context)
    package_id = ''
    try:
        params = json.loads(XMLJSONConverter.xmlToJson(params))
        if 'selected_btz_id' in params['schema']['filter']:
            if params['schema']['filter']['selected_btz_id']:
                package_id = params['schema']['filter']['selected_btz_id']
    except:
        pass
    QtiTheme.setRange('PackageID', package_id)
    QtiTheme.setFilter('ThemeName', "@%s'%s'%%" % ('%' * (not startswith), curvalue))
    QtiTheme.limit(firstrecord, recordcount)
    
    qti_question = QtiQuestionCursor(context)
    
    recordList = ArrayList()
    for row in QtiTheme.iterate():
        rec = DataRecord()
        rec.setId(row.ThemeID)
        rec.setName(unicode(row.ThemeName))
        qti_question.setRange('ThemeID', row.ThemeID)
        rec.addParameter('question_count', str(qti_question.count()))
        recordList.add(rec)

    return ResultSelectorData(recordList, 0)

def procCount(context, main=None, add=None, filterinfo=None, session=None, params=None,
                curvalue=None, startswith=None):
    u'''Функция count селектора ThemeID'''

    QtiTheme = QtiThemeCursor(context)
    package_id = ''
    try:
        params = json.loads(XMLJSONConverter.xmlToJson(params))
        if 'selected_btz_id' in params['schema']['filter']:
            if params['schema']['filter']['selected_btz_id']:
                package_id = params['schema']['filter']['selected_btz_id']
    except:
        pass
    QtiTheme.setRange('PackageID', package_id)
    QtiTheme.setFilter('ThemeName', "@%s'%s'%%" % ('%' * (not startswith), curvalue))
    count = QtiTheme.count()

    return ResultSelectorData(None, count)


