# coding: utf-8
'''
Created on 27.07.2015
☦☦☦☦☦☦☦☦☦☦☦☦☦☦☦☦☦☦☦☦☦☦☦☦☦
@author: tr0glo)|(I╠╣
☦☦☦☦☦☦☦☦☦☦☦☦☦☦☦☦☦☦☦☦☦☦☦☦☦
'''
from java.util import Date
from java.util import Calendar
import json    
from ru.curs.celesta.showcase.utils import XMLJSONConverter
from qt.functions import getImageById, getPrevNextQuestionId, getAttributeValue
from fileRepository._fileRepository_orm import fileCursor
from fileRepository.functions import getRelativePathById
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
from qt._qt_orm import TestingVariantAssignCursor, QtiVariantQuestionCursor, QtiVariantAnswerCursor, \
    QtiQuestionCursor, QtiDestructorCursor, \
    QtiVariantDestructorCursor, QtiVariantDestructorAnswerCursor,\
    QtiResourceCursor, QtiVariantParamsCursor


def cardData(context, main=None, add=None, filterinfo=None, session=None, elementId=None):
    u'''Карточка вопроса с множественным выбором. '''    
    variantQuestionId = main
    QtiVariantQuestion = QtiVariantQuestionCursor(context)
    QtiVariantQuestion.get(variantQuestionId)
    variantId = QtiVariantQuestion.VariantID
    QtiVariantQuestion.setRange('VariantID',variantId)
    QtiVariantQuestion.orderBy('QuestionNumber')
    questionNumber = QtiVariantQuestion.QuestionNumber
    questionCount = QtiVariantQuestion.count()
    
    QtiQuestion = QtiQuestionCursor(context)
    QtiQuestion.get(QtiVariantQuestion.QuestionID)    
    questionHtml = QtiQuestion.QuestionHtml if QtiQuestion.QuestionHtml is not None else ''
    imgId = QtiQuestion.QuestionImg
    QtiResource = QtiResourceCursor(context)
    if imgId:
        imagesJson = json.loads(getImageById(QtiResource, imgId, isImage=False))
        if imagesJson:
            imageFiles = {'image_file': []}
            file_cursor = fileCursor(context)
            imageItems = imagesJson['question_img']
            if isinstance(imageItems, dict):
                imageItems = [imageItems]
            for imageItem in imageItems:
                imageItemId = imageItem['@id']
                if file_cursor.tryGet(imageItemId):                        
                    imageFiles['image_file'].append({'#text': '/'.join(getRelativePathById(context, str(imageItemId), file_version_id=None))})                    
                else:
                    imageFiles['image_file'].append({'#text': ''})
            file_cursor.close()
            questionImg = imageFiles
    else:
        questionImg = ''
    QtiQuestion.close() 
    
    TVA = TestingVariantAssignCursor(context)
    TVA.get(variantId)
    if TVA.AlgorithmTestingID == 1:
        testingAlgorithm = u'Тестирование для самоконтроля'
    elif TVA.AlgorithmTestingID == 2:
        testingAlgorithm = u'Аудиторное тестирование'
    else:
        testingAlgorithm = u'Тестирование'
    TVA.close()
        
    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 = QtiVariantAnswerCursor(context)    
    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'
    QtiVariantAnswer.close()
    
    optionList = []
    resultList = []
    letter = ord('A')
    
    QtiDestructor = QtiDestructorCursor(context)    
    QtiVariantDestructor = QtiVariantDestructorCursor(context)
    QtiVariantDestructor.setRange('VariantQuestionID',variantQuestionId)
    QtiVariantDestructor.orderBy('VariantDestructorID')    
    QtiVariantDestructorAnswer = QtiVariantDestructorAnswerCursor(context)
    for QtiVariantDestructor in QtiVariantDestructor.iterate():
        QtiDestructor.get(QtiVariantDestructor.DestructorID)
        variantDestructorId = QtiVariantDestructor.VariantDestructorID
        destructorHtml = QtiDestructor.DestructorHtml if QtiDestructor.DestructorHtml is not None else ''
        destructorHtml2 = QtiDestructor.DestructorHtml2 if QtiDestructor.DestructorHtml2 is not None else ''
        destructorImg = '<img src="getImage?proc=spQtiGetTestImage&params=%s&responsetype=jpeg" />' % QtiDestructor.DestructorImg\
        if QtiDestructor.DestructorImg is not None else ''
        
        optionList.append({"id":variantDestructorId,
                            "letter":chr(letter),
                            "destructorHTML": destructorHtml + destructorImg + destructorHtml2
                            })
        letter += 1
        checked = '1_' if testingStatus != '0' else '0_'
        
        QtiVariantDestructorAnswer.setRange('VariantDestructorID',QtiVariantDestructor.VariantDestructorID)
        if QtiVariantDestructorAnswer.tryFirst():
            if QtiVariantDestructorAnswer.IsTrue:
                checked += '1'
            else:
                checked += '0'
        else:
            checked += '0'
        resultList.append({"id":variantDestructorId,
                           "checked":checked})
    
    QtiDestructor.close()
    QtiVariantDestructor.close()
    QtiVariantDestructorAnswer.close()    
    
    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":'2',
                        'variantId': variantId,
                        "skipQuestions": skipQuestions,
                        "testingStatus": testingStatus,
                        "captchaText":'',
                        "images": questionImg,
                        "question": {
                            "@number": questionNumber,
                            "@isLastQuestion":'1' if nextVariantQuestionId == 'ID_FINISH' else '0',
                            "@timeout":timeout,
                            "#text":questionHtml},# + questionImg + questionHtml2 + ']]>'
                        "options":{"option":optionList}},
                        "result":{"option":resultList}}}
    
    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"}}]}}]}}

    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)
