# coding: utf-8

import json
from java.util import ArrayList
from qt._qt_orm import QtiPackageCursor, QtiThemeCursor, \
    QtiPackageAttributeCursor, QtiQuestionCursor, QtiDestructorCursor
import uuid
import datetime


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'''Данные для карточки.'''

    # Структура данных
    xformsdata = {
        'schema': {
            '@xmlns':'',
            'data': {
                'faculty_name': '',
                'spec_id': '',
                'spec_name': '',            
                'spec_param': '23',
                'selected_btz_id': '',
                'selected_btz_name': '',
                'selected_btz_status': 'ready',
                'theme_id': '',
                'theme_name': ''
            },
            'questions': ''
        }
    }

    # Первоначальная xformssettings
    xformssettings = {
        'properties': {
            'event': [{
                '@name': 'single_click',
                '@linkId': '1',
                'action': {
                    "#sorted": [
                        {'main_context': 'current'},
                        {"navigator": {"@refresh": "true"}},
                        {'datapanel': {
                            '@type': 'current',
                            '@tab': 'current',
                            'element': {
                                '@id': 'webThemeGrid',
                                'add_context': ''
                            }
                        }
                    }]}},
                {'@name': 'single_click',
                '@linkId': '2',
                'action': {
                    '@keep_user_settings': 'true',
                    "#sorted": [
                        {'main_context': 'current'},
                        {'datapanel': {
                            '@type': 'current',
                            '@tab': 'current',
                            'element': {
                                '@id': 'webThemeGrid',
                                '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'''Сохранение карточки.'''
    session= json.loads(session)
    
    data_dict = json.loads(xformsdata)
    data = data_dict['schema']['data']
    urlparams = session['sessioncontext']['urlparams']['urlparam']
    for urlparam in urlparams:
        if urlparam["@name"] == "package":
            package_id = urlparam["@value"][0]
    QtiTheme = QtiThemeCursor(context)
    QtiQuestion = QtiQuestionCursor(context)   
    QtiQuestion1 = QtiQuestionCursor(context)
    QtiDestructor = QtiDestructorCursor(context)
    QtiDestructor1 = QtiDestructorCursor(context)    
    
    # Вычисляется ThemeOrder.   
    QtiTheme.setRange('PackageID', package_id)
    QtiTheme.orderBy('ThemeOrder')
    if QtiTheme.tryLast():
        order = int(QtiTheme.ThemeOrder) + 1
    else:
        order = 1
    QtiTheme.clear()
    
    # Добавляется тема.   
    new_id = uuid.uuid4()  
    if data['theme_id']:
        QtiTheme.ThemeID = new_id
        QtiTheme.ThemeName = data['theme_name']
        QtiTheme.ThemeOrder = order
        QtiTheme.PackageID = package_id
        QtiTheme.insert()
        
    # Добавляются вопросы.
    # Если выбраны вопросы.     
    if data_dict['schema']['questions']:
        questions = data_dict['schema']['questions']['question']
        if isinstance(questions, dict):
            questions = [questions]            
        for question in questions:
            question_id = question['@id']
            QtiQuestion.get(question_id)
            QtiDestructor.setRange('QuestionID', QtiQuestion.QuestionID)        
            QtiQuestion1.clear()
            QtiQuestion1.copyFieldsFrom(QtiQuestion)
            QtiQuestion1.QuestionID = uuid.uuid4()
            QtiQuestion1.ThemeID = new_id
            QtiQuestion1.insert()   
            for QtiDestructor in QtiDestructor.iterate():
                QtiDestructor1.clear()
                QtiDestructor1.copyFieldsFrom(QtiDestructor)
                QtiDestructor1.DestructorID = uuid.uuid4()
                QtiDestructor1.QuestionID = QtiQuestion1.QuestionID
                QtiDestructor1.insert()
    # Если не выбраны вопросы.            
    else:  
        QtiQuestion.setRange('ThemeID', data['theme_id'])
        for QtiQuestion in QtiQuestion.iterate():
            QtiDestructor.setRange('QuestionID', QtiQuestion.QuestionID)
            QtiQuestion1.clear()
            QtiQuestion1.copyFieldsFrom(QtiQuestion)
            QtiQuestion1.QuestionID = uuid.uuid4()
            QtiQuestion1.ThemeID = new_id
            QtiQuestion1.insert()        
            for QtiDestructor in QtiDestructor.iterate():
                QtiDestructor1.clear()
                QtiDestructor1.copyFieldsFrom(QtiDestructor)
                QtiDestructor1.DestructorID = uuid.uuid4()
                QtiDestructor1.QuestionID = QtiQuestion1.QuestionID
                QtiDestructor1.insert()