# coding: utf-8
'''
Created on 27.02.2015

@author: v.popov
'''

from java.util import ArrayList
from qt._qt_orm import QtiPackageCursor, 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 procCount(context, main=None, add=None, filterinfo=None, session=None, params=None,
                curvalue=None, startswith=None):
    u'''Функция count селектора PackageID '''

    QtiPackage = QtiPackageCursor(context)
    if params:
        paramsJson = json.loads(XMLJSONConverter.xmlToJson(params))
        if 'selected_btz_status' in paramsJson['schema']['filter']:
            QtiPackage.setRange('Status', paramsJson['schema']['filter']['selected_btz_status'])
    QtiPackage.setFilter('PackageName', "@%s'%s'%%" % ('%' * (not startswith), curvalue))
    count = QtiPackage.count()

    return ResultSelectorData(None, count)

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

    QtiPackage = QtiPackageCursor(context)
    if params:
        paramsJson = json.loads(XMLJSONConverter.xmlToJson(params))
        if 'selected_btz_status' in paramsJson['schema']['filter']:
            QtiPackage.setRange('Status', paramsJson['schema']['filter']['selected_btz_status'])
    QtiPackage.setFilter('PackageName', "@%s'%s'%%" % ('%' * (not startswith), curvalue))
    QtiPackage.limit(firstrecord, recordcount)
    QtiPackage.orderBy('DateCreated desc')
    
    qti_theme = QtiThemeCursor(context)
    qti_question = QtiQuestionCursor(context)    
    
    recordList = ArrayList()
    for row in QtiPackage.iterate():
        rec = DataRecord()
        rec.setId(row.PackageID)
        rec.setName(u'%s - %s - %s' % (unicode(row.PackageName), unicode(row.DateCreated), unicode(row.PackageID)))
        count = 0
        qti_theme.setRange('PackageID', row.PackageID)
        for qti_theme in qti_theme.iterate():
            qti_question.setRange('ThemeID', qti_theme.ThemeID)
            count += qti_question.count()
        rec.addParameter('question_count', str(count))
        recordList.add(rec)

    return ResultSelectorData(recordList, 0)
