# coding: utf-8

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

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 селектора QuestionID '''

    QtiQuestion = QtiQuestionCursor(context)
    theme_id = ''
    try:
        params = json.loads(XMLJSONConverter.xmlToJson(params))
        if 'theme_id' in params['schema']['filter']:
            if params['schema']['filter']['theme_id']:
                theme_id = params['schema']['filter']['theme_id']
    except:
        pass
    QtiQuestion.setRange('ThemeID', theme_id)
    QtiQuestion.setFilter('QuestionHtml', "@%s'%s'%%" % ('%' * (not startswith), curvalue))
    QtiQuestion.limit(firstrecord, recordcount)
    recordList = ArrayList()
    for row in QtiQuestion.iterate():
        rec = DataRecord()
        rec.setId(row.QuestionID)
        name = re.sub(r'\<[^>]*\>', "", row.QuestionHtml)
        rec.setName(unicode(re.sub(r'\&[^;]*\;', "", name)))
        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 селектора QuestionID '''

    QtiQuestion = QtiQuestionCursor(context)
    theme_id = ''
    try:
        params = json.loads(XMLJSONConverter.xmlToJson(params))
        if 'theme_id' in params['schema']['filter']:
            if params['schema']['filter']['theme_id']:
                theme_id = params['schema']['filter']['theme_id']
    except:
        pass
    QtiQuestion.setRange('ThemeID', theme_id)
    QtiQuestion.setFilter('QuestionHtml', "@%s'%s'%%" % ('%' * (not startswith), curvalue))
    count = QtiQuestion.count()

    return ResultSelectorData(None, count)