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

# from java.sql import Timestamp
from java.util import Calendar, Date
import json
# from uuid import uuid4
from qt._qt_orm import TestingVariantAssignCursor, QtiVariantCursor, \
    QtiVariantQuestionCursor, QtiVariantAnswerCursor, ContentCursor, \
    Content_AttributeValueCursor, listAttributeContentCursor, \
    QtiPackageAttributeCursor, QtiQuestionCursor, QtiVariantDestructorCursor, \
    QtiVariantDestructorAnswerCursor
# from qt.navigator import getAttributeValue
from ru.curs.celesta.showcase.utils import XMLJSONConverter
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)
    QtiVariantQuestion = QtiVariantQuestionCursor(context)
    QtiVariantAnswer = QtiVariantAnswerCursor(context)
    QtiQuestion = QtiQuestionCursor(context)
    QtiVariantDestructor = QtiVariantDestructorCursor(context)
    QtiVariantDestructorAnswer = QtiVariantDestructorAnswerCursor(context)
#     Content = ContentCursor(context)
#     Content_Attribute = Content_AttributeValueCursor(context)
#     listAttributeContent = listAttributeContentCursor(context)    
    xformssettings = {"properties":{"event":[]}}    
    
    xformssettings['properties']['event'].append({"@name":"single_click",
                                                 "@linkId": "1099",
                                                 "action":{
                                                    "#sorted": [
                                                        {"navigator":
                                                            {"@element":'ID_FINISH'}}]}})
    
    variantId = main
    
    TVA.get(variantId)
    QtiVariant.get(variantId)
    
    variantName = QtiVariant.VariantName
    packageId = TVA.PackageID
    
    QtiPackageAttribute.setRange('PackageID',packageId)

    subject = ''
    QtiPackageAttribute.setRange('AttributeName',u'Учебная дисциплина')
    if QtiPackageAttribute.tryFirst():
        subject = QtiPackageAttribute.AttributeValue
    
    module = ''
    QtiPackageAttribute.setRange('AttributeName',u'Модуль')
    if QtiPackageAttribute.tryFirst():
        module = QtiPackageAttribute.AttributeValue
    
    questionsList = list()
    QtiVariantQuestion.setRange('VariantID',variantId)
    QtiVariantQuestion.orderBy('QuestionNumber')
    questionLeft = 0
    #Цикл по вопросам, определения количества отвеченыз вопросов, формирование списка вопросов и определение для каждого вопроса наличия ответа
    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'
            questionLeft += 1
        else:
            answered = '1'
        
        qNumber = QtiVariantQuestion.QuestionNumber
        redirectUrl = '''javascript:gwtXFormSave('xformId','%s',
            Writer.toString(getSubformInstanceDocument('xformId_mainModel', 'xformId_mainInstance')))'''%(qNumber)
        
        QtiQuestion.get(QtiVariantQuestion.QuestionID)
        questionHtml = QtiQuestion.QuestionHtml
        questionHtml.replace('&nbsp','&amp;nbsp')
        questionsList.append({"@answered":answered,
                              "@num": qNumber,
                              "@redirectUrl":redirectUrl,
                              "#text":questionHtml})
        
        xformssettings['properties']['event'].append({"@name":"single_click",
                                                 "@linkId": QtiVariantQuestion.QuestionNumber,
                                                 "action":{
                                                    "#sorted": [
                                                        {"navigator":
                                                            {"@element":QtiVariantQuestion.VariantQuestionID}}]}})        
    
    if TVA.AlgorithmTestingID == 1:
        testingAlgorithm = u'Тестирование для самоконтроля'
    elif TVA.AlgorithmTestingID == 2:
        testingAlgorithm = u'Aудиторное тестирование'
    else:
        testingAlgorithm = u'Тестирование'    

    #Проверка на завершения времени тестироания
    QtiVariantAnswer.setRange('VariantID',variantId)
    QtiVariantAnswer.first()
    if QtiVariantAnswer.TimeFinish is not None:
        testingStatus = '1'
    elif QtiVariantAnswer.TimeFinish is None and Date() > QtiVariantAnswer.TimeEnd:
        testingStatus = '2'
    else:
        testingStatus = '0'
 
    calNow = Calendar.getInstance()
    timeNow = Date()
    calNow.setTime(timeNow)
 
    calEnd = Calendar.getInstance()
    calEnd.setTime(QtiVariantAnswer.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))
  
    xformsdata = {"schema":{"@xmlns":"",
                        "testDescription": {
                                "testingAlgorithm": testingAlgorithm,
                                'variantId': variantId,
                                "subject":subject,
                                "module":module,
                                "questionsLeft": questionLeft,
                                "testingStatus":testingStatus,
                                "personPhoto": '',
                                "contentCard":'true',
                                "js": js},
                        "questions": {"question": questionsList}}}

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

        