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

@author: v.popov
'''

# import datetime
# from java.util import ArrayList
import json
# from uuid import uuid4
# import uuid

from author._author_orm import serviceCatalogCursor
from qt._qt_orm import QtiPackageCursor, QtiThemeCursor, \
    QtiPackageAttributeCursor, QtiQuestionCursor, QtiDestructorCursor, \
    listAttributeContentCursor, ContentCursor, Content_AttributeValueCursor
from common.grainssettings import SettingsManager
from ru.curs.celesta.showcase.utils import XMLJSONConverter
from suds.client import Client


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




def cardData(context, main=None, add=None, filterinfo=None, session=None, elementId=None):
    u'''Данные для карточки.'''
    
    session = json.loads(session)
    currentRecordId = session["sessioncontext"]['related']['gridContext']['currentRecordId']
    # Структура данных
    xformsdata = {  
        'schema':{  
            '@xmlns':'',
            'data':{  
                    'service_id':'',
                    'service_name':'',
                    'service_address':'',
                    'currentRecordId':currentRecordId,
            }
        }
    }




    # Первоначальная xformssettings
    xformssettings = {  
        'properties': {  
            'event': [  
                {  
                    '@name': 'single_click',
                    '@linkId': '1',
                    'action': {
                        "#sorted": [
                            {'main_context': 'current'},
                            {'datapanel': {  
                              '@type': 'current',
                              '@tab': 'current',
                              'element': [  
                                  {  
                                      '@id': 'publishBtzCard',
                                      'add_context': 'hide'
                                  }

                              ]
                            }
                          }]}
                }
            ]
        }
    }
    

    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 = json.loads(xformsdata)
    serviceCatalog = serviceCatalogCursor(context)
    qti_package = QtiPackageCursor(context)
    qti_question = QtiQuestionCursor(context)
    qti_theme = QtiThemeCursor(context)
    qti_destructor = QtiDestructorCursor(context)
    qti_package_attribute = QtiPackageAttributeCursor(context)
    list_attribute_content = listAttributeContentCursor(context)
    content = ContentCursor(context)
    content_attribute_value = Content_AttributeValueCursor(context)
     
    serviceId = int(data['schema']['data']['service_id'])
    
    serviceCatalog.get(serviceId)
    
    url = serviceCatalog.link
    
    
    currentPackageId = session['sessioncontext']['related']['gridContext']['currentRecordId']
    
    request = {'test':{},
               'params':{}}
    
    qti_package.get(currentPackageId)
    
    request['test']['package_id'] = qti_package.PackageID
    request['test']['package_name'] = qti_package.PackageName
    request['test']['package_version'] = qti_package.PackageVersion
#     request['test']['date_created'] = qti_package.DateCreated
    request['test']['status'] = qti_package.Status
    request['test']['attributes'] = []
    
    qti_package_attribute.setRange('PackageID', currentPackageId)
    for attribute in qti_package_attribute.iterate():
        request['test']['attributes'].append({'id':attribute.AttributeID,
                                              'name':attribute.AttributeName,
                                              'value': attribute.AttributeValue
                                              })
    
    request['test']['themes'] = []
    
    qti_theme.setRange('PackageID', currentPackageId)
    for theme in qti_theme.iterate():
        themeDict = dict()
        themeDict['id'] = theme.ThemeID
        themeDict['name'] = theme.ThemeName
        themeDict['order'] = theme.ThemeOrder
        themeDict['questions'] = []
        qti_question.setRange('ThemeID', theme.ThemeID)
        for question in qti_question.iterate():
            questionDict = dict()
            questionDict['id'] = question.QuestionID
            questionDict['html'] = question.QuestionHtml
            questionDict['type'] = question.QuestionType
            questionDict['order'] = question.QuestionOrder
            questionDict['destructors'] = []
            qti_destructor.setRange('QuestionID', question.QuestionID)
            for destructor in qti_destructor.iterate():
                destructorDict = dict()
                destructorDict['id'] = destructor.DestructorID
                destructorDict['html'] = destructor.DestructorHtml
                destructorDict['answerText'] = destructor.AnswerText
                destructorDict['isTrue'] = destructor.IsTrue
                destructorDict['order'] = destructor.DestructorOrder
                questionDict['destructors'].append(destructorDict)
            themeDict['questions'].append(questionDict)
        request['test']['themes'].append(themeDict)
            
        
    request['test']['content'] = []
    
    content.setRange('PackageID', currentPackageId)
    for content in content.iterate():
        contentDict = dict()
        contentDict['id'] = content.ContentID
        contentDict['params'] = []
        content_attribute_value.setRange('ContentID', content.ContentID)
        for param in content_attribute_value.iterate():
            paramDict = dict()
            paramDict['id'] = param.AttributeContentID
            paramDict['value'] = param.AttributeValue
            contentDict['params'].append(paramDict)
        request['test']['content'].append(contentDict)
        
    settings_manager = SettingsManager()
    pin = settings_manager.getGrainSettings('parameter[@name="pin"]/@value', 'author')[0]
    address = settings_manager.getGrainSettings('parameter[@name="address"]/@value', 'author')[0]
    request['params']['pin'] = pin
    request['params']['address'] = address 
    
    client = Client(url)
    try:
        answer = client.service.handle(request=json.dumps(request), procName="qt.webservices.webservices.publishBTZ.celesta")
    except:
        return context.error(u'Ошибка при публикации БТЗ')
    answer = json.loads(answer)
    if answer['answer']['status'] == '0':
        return context.error(answer['answer']['message'])
    elif answer['answer']['status'] == '1':
        return context.message(answer['answer']['message'])



    
