# 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
from time import time
import json
import random
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 completeTest, 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'''Карточка вопрса-классификации. '''
    begin = time()
    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)
    QtiResource = QtiResourceCursor(context)
    Content = ContentCursor(context)
    Content_Attribute = Content_AttributeValueCursor(context)
    listAttributeContent = listAttributeContentCursor(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)
    print 'start', time() - begin
    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))
    print 'load', time() - begin
#     answerCount = 0
#     for question in QtiVariantQuestion.iterate():
#         QtiVariantDestructor.setRange('VariantQuestionID',question.VariantQuestionID)
#         for VariantDestructor in QtiVariantDestructor.iterate():
#             QtiVariantDestructorAnswer.setRange('VariantDestructorID',VariantDestructor.VariantDestructorID)
#             if QtiVariantDestructorAnswer.count() > 0:
#                 answerCount += 1
    print 'countquest', time() - begin
    TVA.get(variantId)
    if TVA.AlgorithmTestingID == 1:
        testingAlgorithm = u'Тестирование для самоконтроля'
    elif TVA.AlgorithmTestingID == 2:
        testingAlgorithm = u'Аудиторное тестирование'
    else:
        testingAlgorithm = u'Тестирование'
        
    questionHeader = u'Вопрос %s из %s'%(questionNumber,questionCount)
    print 'header', time() - begin
    
    
    #Определение идентификаторов следующего и предыдушго вопросов
#     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)
    
    optionList = []
    resultList = []
    letter = ord('A')
    QtiVariantDestructor.orderBy('VariantDestructorID')
    print 'prequest', time() - begin

    
    answerList = list()
    answerTextSet = set()
    
    #Нужно ли показывать правильные ответы
    correctAnswerFlag = getShowCorrectAnswerPermission(context, session, variantId)
    
    #Формируем список вариантов для классификации и список классификаторов
    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 =  getImageById(QtiResource,QtiDestructor.DestructorImg)
        
        answerDestructorId = ''
        answerText = ''
        QtiVariantDestructorAnswer.setRange('VariantDestructorID',QtiVariantDestructor.VariantDestructorID)
        if QtiVariantDestructorAnswer.tryFirst():
            answerDestructorId = QtiVariantDestructorAnswer.DestructorID
            QtiDestructor.get(answerDestructorId)
            answerText = QtiDestructor.AnswerText

        
        optionList.append({"@id":variantDestructorId,
                            "@letter":chr(letter),
                            "opt": destructorHtml + destructorImg + destructorHtml2,
                            "answ":{"@DestructorID":answerDestructorId,
                                    "#text":answerText}
                            })
        

        
        QtiDestructor.get(QtiVariantDestructor.DestructorID)
        
        if correctAnswerFlag:
            optionList[-1]['correctAnsw'] = {"@DestructorID":QtiDestructor.DestructorID,
                                               "#text":QtiDestructor.AnswerText}

        if QtiDestructor.AnswerText not in answerTextSet:
            answerList.append({"@DestructorID":QtiVariantDestructor.DestructorID,
                               "#text":QtiDestructor.AnswerText
                       })
            answerTextSet.add(QtiDestructor.AnswerText)
        
        letter += 1




    print 'calcList', time() - begin
    calNow = Calendar.getInstance()
    timeNow = Date()
    calNow.setTime(timeNow)
    
    calEnd = Calendar.getInstance()
    calEnd.setTime(timeEnd)
    
    print 'quest', time() - begin
    js = '''javascript:prepareClassifDnD();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":'6',
                            'variantId': variantId,
                            "skipQuestions": skipQuestions,
                            "testingStatus": testingStatus,
                            "showCorrect":'true' if correctAnswerFlag else 'false',
                            "question":
                                {"@number": questionNumber,
                                 "@isLastQuestion":'1' if nextVariantQuestionId == 'ID_FINISH' else '0',
                                 "@timeout":timeout,
                                "#text":questionHtml + questionImg# + questionHtml2 + ']]>'
                                 },
                            "options":{"option":optionList},
                            "answers":{"answer":answerList}},
                        "result":''}}

    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)
    print 'finish', time() - begin
    return JythonDTO(data, settings)





        