# coding: utf-8
'''
Created on 27.07.2015
☦☦☦☦☦☦☦☦☦☦☦☦☦☦☦☦☦☦☦☦☦☦☦☦☦
@author: tr0glo)|(I╠╣
☦☦☦☦☦☦☦☦☦☦☦☦☦☦☦☦☦☦☦☦☦☦☦☦☦
'''


from java.sql import Timestamp
from java.util import Date
from java.util import Calendar
import json
from uuid import uuid4

from qt._qt_orm import TestingVariantAssignCursor, QtiVariantCursor, \
    QtiVariantQuestionCursor, QtiVariantAnswerCursor, ContentCursor, \
    Content_AttributeValueCursor, listAttributeContentCursor, \
    QtiPackageAttributeCursor, QtiQuestionCursor, QtiDestructorCursor, \
    QtiVariantDestructorCursor, QtiVariantDestructorAnswerCursor,\
    QtiResourceCursor, QtiVariantParamsCursor
    

from ru.curs.celesta.showcase.utils import XMLJSONConverter
from qt.functions import getImageById, getShowCorrectAnswerPermission,\
    getPrevNextQuestionId, getAttributeValue


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)

    TVA = TestingVariantAssignCursor(context)
    QtiVariant = QtiVariantCursor(context)
    QtiPackageAttribute = QtiPackageAttributeCursor(context)
    QtiQuestion = QtiQuestionCursor(context)
    QtiVariantQuestion = QtiVariantQuestionCursor(context)
    QtiVariantAnswer = QtiVariantAnswerCursor(context)
    QtiDestructor = QtiDestructorCursor(context)
    QtiVariantDestructor = QtiVariantDestructorCursor(context)
    QtiVariantDestructorAnswer = QtiVariantDestructorAnswerCursor(context)
    Content = ContentCursor(context)
    Content_Attribute = Content_AttributeValueCursor(context)
    listAttributeContent = listAttributeContentCursor(context)
    QtiResource = QtiResourceCursor(context)
    
    variantQuestionId = main
    QtiVariantQuestion.get(variantQuestionId)
    variantId = QtiVariantQuestion.VariantID
    QtiVariantQuestion.setRange('VariantID',variantId)
    QtiVariantQuestion.orderBy('QuestionNumber')
    questionNumber = QtiVariantQuestion.QuestionNumber
    questionCount = QtiVariantQuestion.count()
    QtiQuestion.get(QtiVariantQuestion.QuestionID)
    #Получаем текст вопроса
    questionHtml = QtiQuestion.QuestionHtml if QtiQuestion.QuestionHtml is not None else ''
    questionHtml2 = QtiQuestion.QuestionHtml2 if QtiQuestion.QuestionHtml2 is not None else ''
    questionImg = ''''<br/>%s'''%(getImageById(QtiResource,QtiQuestion.QuestionImg)) if QtiQuestion.QuestionImg is not None else ''   

    TVA.get(variantId)
    if TVA.AlgorithmTestingID == 1:
        testingAlgorithm = u'Тестирование для самоконтроля'
    elif TVA.AlgorithmTestingID == 2:
        testingAlgorithm = u'Аудиторное тестирование'
    else:
        testingAlgorithm = u'Тестирование'
        
    questionHeader = u'Вопрос %s из %s'%(questionNumber,questionCount)

    #Получение идентификаторов следующего и предыдущего вопросов
#     QtiVariantQuestion.setRange("QuestionNumber",1)
#     QtiVariantQuestion.first()
#     
#     firstVariantQuestionId = QtiVariantQuestion.VariantQuestionID
#     
#     QtiVariantQuestion.setRange("QuestionNumber")
#     QtiVariantQuestion.get(variantQuestionId)
#     
#     nextVariantQuestionId = 'ID_FINISH'
#     if QtiVariantQuestion.navigate('>'):
#         nextVariantQuestionId = QtiVariantQuestion.VariantQuestionID
#     
#     prevVariantQuestionId = firstVariantQuestionId
#     QtiVariantQuestion.get(variantQuestionId)
#     if QtiVariantQuestion.navigate('<'):
#         prevVariantQuestionId = QtiVariantQuestion.VariantQuestionID
        
    prevVariantQuestionId, nextVariantQuestionId = getPrevNextQuestionId(context, QtiVariantQuestion, variantQuestionId)
    QtiVariantQuestion.close()
        
    QtiVariantAnswer.setRange('VariantID',variantId)
    QtiVariantAnswer.first()
    
    #Проверка завершения тестирования
    timeEnd = QtiVariantAnswer.TimeEnd
    timeout = '1' if QtiVariantAnswer.TimeEnd < Date() else '0'
    if QtiVariantAnswer.TimeFinish is None and QtiVariantAnswer.TimeEnd < Date():
        testingStatus = '2'
    elif QtiVariantAnswer.TimeFinish is not None:
        testingStatus = '1'
    else:
        testingStatus = '0'
    
    QtiVariantDestructor.setRange('VariantQuestionID',variantQuestionId)
    
    QtiVariantDestructor.first()
    
    variantDestructorId = QtiVariantDestructor.VariantDestructorID
    
    QtiDestructor.get(QtiVariantDestructor.DestructorID)
    
    #Надо ли показвать правильный ответ
    correctAnswerFlag = getShowCorrectAnswerPermission(context, session, variantId)
    
    correctAnswer = ''
    if correctAnswerFlag:
        correctAnswer = QtiDestructor.DestructorHtml
    
    answerText = ''
    #Получение предыдущего ответа на вопрос
    QtiVariantDestructorAnswer.setRange('VariantDestructorID',variantDestructorId)
    if QtiVariantDestructorAnswer.tryFirst():
        if QtiVariantDestructorAnswer.DestructorText is not None:
            answerText = QtiVariantDestructorAnswer.DestructorText

    
    calNow = Calendar.getInstance()
    timeNow = Date()
    calNow.setTime(timeNow)
    
    calEnd = Calendar.getInstance()
    calEnd.setTime(timeEnd)
    #Скрипт выставки счётчика оставшегося на тестирование времени
    js = '''javascript:injectCounter(new Date(%s,%s,%s,%s,%s,%s),new Date(%s,%s,%s,%s,%s,%s))'''%\
    (calEnd.get(Calendar.YEAR),calEnd.get(Calendar.MONTH),calEnd.get(Calendar.DAY_OF_MONTH),\
     calEnd.get(Calendar.HOUR_OF_DAY),calEnd.get(Calendar.MINUTE),calEnd.get(Calendar.SECOND),\
     calNow.get(Calendar.YEAR),calNow.get(Calendar.MONTH),calNow.get(Calendar.DAY_OF_MONTH),\
     calNow.get(Calendar.HOUR_OF_DAY),calNow.get(Calendar.MINUTE),calNow.get(Calendar.SECOND))
    
    QtiVariantParams = QtiVariantParamsCursor(context)
    skipQuestions = getAttributeValue(QtiVariantParams, variantId, 'SkipQuestions')
    QtiVariantParams.close()
        
    xformsdata = {"schema":{"@xmlns":"",
                        "description": {
                                    "testingAlgorithm": testingAlgorithm,
                                    "js":js,
                                    "questionHeader":questionHeader,
                                    "questionType":'3',
                                    'variantId': variantId,
                                    "testingStatus": testingStatus,
                                    "skipQuestions": skipQuestions,
                                    "showCorrect":'true' if correctAnswerFlag else 'false',
                                    "correctAnswer":correctAnswer,
                                    "captchaText":'',
                                    "question":
                                        {"@number": questionNumber,
                                         "@isLastQuestion":'1' if nextVariantQuestionId == 'ID_FINISH' else '0',
                                         "@timeout":timeout,
                                        "#text":questionHtml + questionImg# + questionHtml2
                                         },
#                                     "options":{"option":optionList}
                                   },
                        "result":{"option":{"@id":variantDestructorId,
                                            "answer":answerText}}


                        }
              }    
    
    
    #Переходы к списку вопросов, результату тестирования, предыдущему и следующему вопросам
    xformssettings = {"properties":{"event":[{"@name":"single_click",
                                             "@linkId": "1",
                                             "action":{
                                                  "#sorted": [
                                                      {"navigator":
                                                          {"@element": prevVariantQuestionId}
                                                      }
                                                  ]}
                                             },
                                             {"@name":"single_click",
                                             "@linkId": "2",
                                             "action":{
                                                  "#sorted": [
                                                      {"navigator":
                                                          {"@element": nextVariantQuestionId}
                                                      }
                                                  ]}
                                             },
                                             {"@name":"single_click",
                                             "@linkId": "3",
                                             "action":{
                                                  "#sorted": [
                                                      {"navigator":
                                                          {"@element": "ID_FINISH"}
                                                      }
                                                  ]}
                                             },
                                             {"@name":"single_click",
                                             "@linkId": "4",
                                             "action":{
                                                  "#sorted": [
                                                      {"navigator":
                                                          {"@element": "ID_CONTENTS"}
                                                      }
                                                  ]}
                                             }
                                             ]
                                    }
                      }


    #print XMLJSONConverter(input=xformsdata).parse(), XMLJSONConverter(input=xformssettings).parse()
    data = XMLJSONConverter.jsonToXml(json.dumps(xformsdata))
    data = data.replace('&nbsp;','&amp;nbsp;')
    settings = XMLJSONConverter.jsonToXml(json.dumps(xformssettings))
#     data = data.replace('&lt;','<')
#     data = data.replace('&gt','>')
#     raise Exception(data)
#    raise Exception(settings)
    return JythonDTO(data, settings)


