# coding: utf-8
'''
Created on 10.03.2015

@author: v.popov
'''

import json
from java.util import ArrayList
from qt._qt_orm import QtiPackageCursor, QtiThemeCursor, \
    QtiPackageAttributeCursor, QtiQuestionCursor, QtiDestructorCursor
# from elc._elc_orm import vw_qti_questionCursor
import uuid
import datetime
from fileRepository.functions import getRelativePathById


try:
    from ru.curs.showcase.core.jython import JythonDTO
    from ru.curs.showcase.core.selector import ResultSelectorData
    from ru.beta2.extra.gwt.ui.selector.api import DataRecord
    from ru.curs.showcase.app.api import UserMessage, MessageType
except:
    from ru.curs.celesta.showcase import JythonDTO, ResultSelectorData, DataRecord, UserMessage, MessageType

from ru.curs.celesta.showcase.utils import XMLJSONConverter
# from journals.functions import personIdFromSID


def cardData(context, main=None, add=None, filterinfo=None, session=None, elementId=None):
    u'''Данные для карточки.'''

    QtiDestructor = QtiDestructorCursor(context)
    QtiQuestion = QtiQuestionCursor(context)
    QtiQuestion.get(json.loads(session)['sessioncontext']['related']['gridContext']['currentRecordId'])
    questionType = int(QtiQuestion.QuestionType)
    
    question_image = None
    if questionType == 7:
        imageId = str(QtiQuestion.QuestionImg)
        if imageId:
            question_image = '/'.join(getRelativePathById(context, imageId, file_version_id=None))
    # Структура данных
    xformsdata = {"schema":
                  {"@xmlns":"",
                    "data":
                        {
                        "question_id": json.loads(session)['sessioncontext']['related']['gridContext']['currentRecordId'],
                        "question_type": questionType,
                        "question_image": question_image,
                        "answers": {"answer": []}}}}

    QtiDestructor.setRange('QuestionID', json.loads(session)['sessioncontext']['related']['gridContext']['currentRecordId'])
    QtiDestructor.orderBy('DestructorOrder')

    answer = xformsdata['schema']['data']['answers']['answer']
    for QtiDestructor in QtiDestructor.iterate():
        answer.append({'id': QtiDestructor.DestructorID,
                       'html': QtiDestructor.DestructorHtml.replace('&nbsp;',' '),
                       'destructor':QtiDestructor.AnswerText.replace('&nbsp;',' ') if QtiDestructor.AnswerText is not None else '',
                       'is_true': "true" if QtiDestructor.IsTrue else 'false',
                       'order': QtiDestructor.DestructorOrder,
                       'color': '#FFFFFF'})
    # Первоначальная xformssettings
    xformssettings = {"properties":{"event":[{"@name":"single_click",
                                             "@linkId": "1",
                                             "action":{
                                                  "@keep_user_settings": "true",
                                                  "#sorted": [
                                                      {"main_context": "current"},
                                                      {"datapanel": {"@type": "current",
                                                                     "@tab": "current",
                                                                     "element": {"@id":'btzAnswerGrid',
                                                                                 "add_context": ""
                                                                                 }
                                                                     }
                                                      }]}
                                             }]
                                    }
                      }


    return JythonDTO(XMLJSONConverter.jsonToXml(json.dumps(xformsdata)), XMLJSONConverter.jsonToXml(json.dumps(xformssettings)))


def cardSave(context, main=None, add=None, filterinfo=None, session=None, elementId=None, xformsdata=None):
    u'''Сохранение карточки. '''

    data_dict = json.loads(xformsdata)
    QtiDestructor = QtiDestructorCursor(context)
    #
    #package_id = data_dict['schema']['data']['package_id']
    question_type = data_dict['schema']['data']['question_type']
    if 'answer' in data_dict['schema']['data']['answers']:
        answers = data_dict['schema']['data']['answers']['answer']
    else:
        answers = []
    #raise Exception(themes)
    if isinstance(answers, dict):
        answers = [data_dict['schema']['data']['answers']['answer']]
    # добавляем - обновляем темы
    for answer in answers:
        if answer['id'] == u'new':
            QtiDestructor.DestructorID = uuid.uuid4()
            QtiDestructor.DestructorHtml = answer['html']
            QtiDestructor.DestructorOrder = answer['order']
            QtiDestructor.QuestionID = data_dict['schema']['data']['question_id']
            QtiDestructor.AnswerText = answer['destructor']
            QtiDestructor.IsTrue = True if answer['is_true'] == 'true' else False
            QtiDestructor.insert()
        else:
            QtiDestructor.get(answer['id'])
            QtiDestructor.DestructorHtml = answer['html']
            QtiDestructor.DestructorOrder = answer['order']
            QtiDestructor.QuestionID = data_dict['schema']['data']['question_id']
            QtiDestructor.IsTrue = True if answer['is_true'] == 'true' else False
            QtiDestructor.AnswerText = answer['destructor']
            QtiDestructor.update()
        #context.message(QtiTheme.asCSVLine())
    # удаляем темы, по которым нет вопросов из тем
    old_theme_ids = [k['id'] for k in answers if k['id'] != '']
    #old_theme_has_q = False
    QtiDestructor.clear()
    QtiDestructor.setRange('QuestionID', data_dict['schema']['data']['question_id'])
    if len(old_theme_ids) < QtiDestructor.count():
        for QtiDestructor in QtiDestructor.iterate():
            if QtiDestructor.DestructorID not in old_theme_ids:
                QtiDestructor.delete()




