# coding: utf-8
'''
Created on 06.03.2015
@author: v.popov
'''

import json
import uuid
from qt._qt_orm import QtiThemeCursor, QtiQuestionCursor, QtiDestructorCursor
from ru.curs.celesta.showcase.utils import XMLJSONConverter
from qt.functions import setAccessPermission
try:
    from ru.curs.showcase.core.jython import JythonDTO
    from ru.curs.showcase.core.selector import ResultSelectorData
    from ru.beta2.extra.gwt.ui.selector.api import DataRecord
    from ru.curs.showcase.app.api import UserMessage, MessageType
except:
    from ru.curs.celesta.showcase import JythonDTO, ResultSelectorData, DataRecord, UserMessage, MessageType


def cardData(context, main=None, add=None, filterinfo=None, session=None, elementId=None):
    u'''Данные для карточки.'''
    session = json.loads(session)
    package_id = session['sessioncontext']['related']['gridContext']['currentRecordId']
    qti_theme = QtiThemeCursor(context)
    qti_question = QtiQuestionCursor(context)
    qti_destructor = QtiDestructorCursor(context)
    qti_theme.setRange('PackageID',package_id)
    count = 0
    errorText = ''
    emptyFlag = False
    for theme in qti_theme.iterate():
        qti_question.setRange('ThemeID',theme.ThemeID)
        count += qti_question.count()
        questionList = []
        for question in qti_question.iterate():
            qti_destructor.setRange('QuestionID',question.QuestionID)
            if qti_destructor.count() == 0:
                questionList.append(str(question.QuestionOrder))
        if questionList:
            errorText += u'В теме "%s" вопросы №%s не содержат вариантов ответа. '%(theme.ThemeName,','.join(questionList))
            emptyFlag = True
    if count == 0:
        emptyFlag = True
        errorText = u'БТЗ не содержит вопросов'
    variant_id = unicode(uuid.uuid4())

    if not add:
        add = 'debug'
    # Структура данных
    xformsdata = {'schema': {  
            '@xmlns':'',
            'data': {  
                'mode_name': '',
                'mode_id': add,
                'variant_id': variant_id,
                'package_id': package_id,
                '@empty':'true' if emptyFlag else 'false',
                '@errorText': errorText}}}

    # Первоначальная xformssettings
    xformssettings = {'properties': {  
            'event': [  
                {'@name': 'single_click',
                 '@linkId': '1',
                 'action': {
                    "#sorted": [
                        {'main_context': 'current'},
                        {'datapanel': {  
                            '@type': 'current',
                            '@tab': 'current',
                            'element': [  
                                {'@id': elementId,
                                 'add_context': 'hide'}]}},
                                {"client": {
                                    "activity": [
                                        {"@id": "debugBTZ",
                                         "@name": "goToTest",
                                         "add_context": u"&mode=%s&package=%s&param=%s" % (add,package_id,variant_id)}]}}]}},
                {'@name': 'single_click',
                 '@linkId': '2',
                 'action': {
                    "@show_in":"MODAL_WINDOW",
                    "#sorted": [
                        {'main_context': 'current'},
                        {'datapanel': {
                            '@type': 'current',
                            '@tab': 'current',
                            'element': [  
                                {'@id': 'testBtzCard',
                                 'add_context': ''}]}}]}}]}}
    
    return JythonDTO(XMLJSONConverter.jsonToXml(json.dumps(xformsdata)), XMLJSONConverter.jsonToXml(json.dumps(xformssettings)))


def cardSave(context, main=None, add=None, filterinfo=None, session=None, elementId=None, xformsdata=None):
    u'''Сохранение карточки. '''
    session = json.loads(session)
    data = json.loads(xformsdata)['schema']['data']
#     package_id = add['package_id']
    variant_id = data['variant_id']
    sid = session['sessioncontext']['sid']
    mode = data['mode_id']
    setAccessPermission(context, sid, mode, variant_id)
    
