# coding: utf-8
'''
Created on 27.07.2015
☦☦☦☦☦☦☦☦☦☦☦☦☦☦☦☦☦☦☦☦☦☦☦☦☦
@author: tr0glo)|(I╠╣
☦☦☦☦☦☦☦☦☦☦☦☦☦☦☦☦☦☦☦☦☦☦☦☦☦
'''
from java.util import Date
from java.sql import Timestamp
import json
from uuid import uuid4

from qt._qt_orm import TestingVariantAssignCursor, QtiVariantCursor, \
    QtiVariantQuestionCursor, QtiVariantAnswerCursor, ContentCursor, \
    Content_AttributeValueCursor, listAttributeContentCursor,\
    QtiPackageAttributeCursor, QtiVariantDestructorCursor,\
    QtiVariantDestructorAnswerCursor, QtiQuestionCursor, QtiVariantParamsCursor
    
from qt.navigator import getAttributeValue
from ru.curs.celesta.showcase.utils import XMLJSONConverter
from qt.functions import completeTest

try:
    from ru.curs.showcase.core.jython import JythonDTO
    from ru.curs.showcase.core.jython import JythonDownloadResult
except:
    from ru.curs.celesta.showcase import JythonDTO
    

def cardData(context, main=None, add=None, filterinfo=None, session=None, elementId=None):
    u'''Карточка резульататов. '''    
    session = json.loads(session)
    
    variantId = main
    completeTest(context,variantId)    

    #Тип тестирования
    testingAlgorithm = u'Тестирование'
    
    TVA = TestingVariantAssignCursor(context)
    TVA.get(variantId)
    if TVA.AlgorithmTestingID == 1:
        testingAlgorithm = u'Тестирование для самоконтроля'
    elif TVA.AlgorithmTestingID == 2:
        testingAlgorithm = u'Аудиторное тестирование'        
    TVA.close()
    
    QtiVariantAnswer = QtiVariantAnswerCursor(context)
    QtiVariantAnswer.setRange('VariantID',variantId)
    QtiVariantAnswer.tryFirst()
    
    #Получаем оценку, балл за тестирование и вычисляем затраченное на тестирование время
    score = QtiVariantAnswer.Score
    mark = QtiVariantAnswer.TestingMark
    secondSpent = (QtiVariantAnswer.TimeFinish.getTime() - QtiVariantAnswer.TimeBegin.getTime())/1000
    QtiVariantAnswer.close()
    
    xformssettings = {"properties": {
                        "event":[
                            {"@name":"single_click",
                             "@linkId": "content",
                             "action":{
                                  "#sorted": [
                                      {"navigator":
                                          {"@element":'ID_CONTENTS'}}]}}]}}
    
    QtiVariantQuestion = QtiVariantQuestionCursor(context)
    QtiVariantQuestion.setRange('VariantID',variantId)
    QtiVariantQuestion.orderBy('QuestionNumber')    
    
    QtiVariantDestructor = QtiVariantDestructorCursor(context)
    QtiVariantDestructorAnswer = QtiVariantDestructorAnswerCursor(context)
    QtiQuestion = QtiQuestionCursor(context)
    
    questionsList = list()
    #Формируем список вопросов и для каждого вопроса определям был ли дан на него ответ, и если был дан ответа, то правильный или неправильный
    for QtiVariantQuestion in QtiVariantQuestion.iterate():
        QtiVariantDestructor.setRange('VariantQuestionID',QtiVariantQuestion.VariantQuestionID)
        questionFlag = True
        for QtiVariantDestructor in QtiVariantDestructor.iterate():
            QtiVariantDestructorAnswer.setRange('VariantDestructorID',QtiVariantDestructor.VariantDestructorID)
            if QtiVariantDestructorAnswer.count() > 0:
                questionFlag = False
                break
        if questionFlag:
            answered = '0'
        else:
            if QtiVariantQuestion.CorrectAnswer:
                answered = '1'
            else:
                answered = '2'
                
        qNumber = QtiVariantQuestion.QuestionNumber
        #Формируем ссылка для переходна вопрос    
        redirectUrl = '''javascript:gwtXFormSave('xformId','%s',
            Writer.toString(getSubformInstanceDocument('xformId_mainModel', 'xformId_mainInstance')))'''%(QtiVariantQuestion.QuestionNumber)
        
        QtiQuestion.get(QtiVariantQuestion.QuestionID)
        questionHtml = QtiQuestion.QuestionHtml
        questionHtml.replace('&nbsp','&amp;nbsp')
        questionHtml2 = u""
        if answered == '2':
            questionHtml2 = QtiQuestion.QuestionHtml2
            if questionHtml2:
                questionHtml2.replace('&nbsp','&amp;nbsp')
            
        questionsList.append({"@answered":answered,
                              "@num": qNumber,
                              "@redirectUrl":redirectUrl,
                              # "#text":questionHtml,
                              "#sorted": [
                                {"questionHtml": questionHtml},
                                {"questionHtml2": questionHtml2}]})
        
        xformssettings['properties']['event'].append({"@name":"single_click",
                                                 "@linkId": qNumber,
                                                 "action":{
                                                    "#sorted": [
                                                        {"navigator":
                                                            {"@element":QtiVariantQuestion.VariantQuestionID}}]}})  
    
    QtiQuestion.close()  
    QtiVariantDestructorAnswer.close()
    QtiVariantDestructor.close()
    QtiVariantQuestion.close()
    
    QtiVariantParams = QtiVariantParamsCursor(context)
    no_protocol = getAttributeValue(QtiVariantParams, variantId, 'NoProtocol')
    QtiVariantParams.close()
    
    xformsdata = {"schema": 
                    {"@xmlns": "",
                    "result": {
                       "testingAlgorithm": testingAlgorithm,
                       "no_protocol": no_protocol,
                       "score": score,
                       "testingMark": mark,
                       "timeSpent": '%s:%s'%(secondSpent/60,'0' + str(secondSpent%60) if secondSpent%60 < 10 else secondSpent%60)},
                    "questions": {"question": questionsList}}}

    data = XMLJSONConverter.jsonToXml(json.dumps(xformsdata))
    data = data.replace('&nbsp;','&amp;nbsp;')
    return JythonDTO(data, XMLJSONConverter.jsonToXml(json.dumps(xformssettings)))
