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

@author: v.popov
'''

import json
from java.util import ArrayList

from qt._qt_orm import QtiPackageCursor, QtiThemeCursor, \
    QtiPackageAttributeCursor, QtiQuestionCursor, QtiDestructorCursor
import uuid
from uuid import uuid4 
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



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

    # Структура данных
    xformsdata = {  
        'schema':{  
            '@xmlns':'',
            'data':{  
                'package_name':'',
                'confirm_author':'false',
                'confirm_reviewer':'false',
                'author_id':'',
                'author_name':'',
                'authorForm':'false',
                'cath_id':'',
                'cath_name':'',
                'use_for_self':'false',
                'use_for_control':'false',
                'year':'',
                'e-mail':'',
                'phone':''
            }
        }
    }

    if add == 'edit':
        QtiPackage = QtiPackageCursor(context)
        QtiPackage.get(json.loads(session)['sessioncontext']['related']['gridContext']['currentRecordId'])
        xformsdata['schema']['data']['package_name'] = QtiPackage.PackageName
#         cath = faculty_departmentCursor(context)
#         author = employeesCursor(context)
#         eorAuthors=eorAuthorsCursor(context)
#         authorForm='false'
#         email=''
#         if QtiPackage.author is not None and QtiPackage.extauthor is None:
#             authorid=QtiPackage.author
#             fio=author.fio if author.tryGet(QtiPackage.author) else ''
#             QtiPackageAttribute = QtiPackageAttributeCursor(context)
#             QtiPackageAttribute.setRange('PackageID', json.loads(session)['sessioncontext']['related']['gridContext']['currentRecordId'])
#             QtiPackageAttribute.setFilter('AttributeName', "@%'mail'%")
#             if QtiPackageAttribute.tryFirst():
#                 email = QtiPackageAttribute.AttributeValue
#             QtiPackageAttribute.setFilter('AttributeName', u"@%'телефон'%")
#             if QtiPackageAttribute.tryFirst():
#                 phone = QtiPackageAttribute.AttributeValue
#             QtiPackageAttribute.setFilter('AttributeName', u"@%'год'%&%'составл'%")
#             if QtiPackageAttribute.tryFirst():
#                 xformsdata['schema']['data']['year'] = QtiPackageAttribute.AttributeValue
# 
#         if QtiPackage.author is None and QtiPackage.extauthor is not None:
#             authorid=QtiPackage.extauthor
#             fio=eorAuthors.fio if eorAuthors.tryGet(QtiPackage.extauthor) else ''
#             authorForm='true'
#             email=eorAuthors.email
#             phone=eorAuthors.tel
#         if QtiPackage.author is None and QtiPackage.extauthor is None:
#             authorid=''
#             fio=''
#             phone=''
#         xformsdata['schema']['data']['package_name'] = QtiPackage.PackageName
#         xformsdata['schema']['data']['confirm_author'] = 'true' if QtiPackage.confirm_author else 'false'
#         xformsdata['schema']['data']['confirm_reviewer'] = 'true' if QtiPackage.confirm_reviewer else 'false'
#         xformsdata['schema']['data']['author_id'] = authorid
#         xformsdata['schema']['data']['author_name'] = fio
#         xformsdata['schema']['data']['authorForm'] = authorForm
#         xformsdata['schema']['data']['cath_id'] = QtiPackage.cath_id
#         xformsdata['schema']['data']['e-mail'] =email
#         xformsdata['schema']['data']['phone']=phone
#         if cath.tryGet(QtiPackage.cath_id):
#             xformsdata['schema']['data']['cath_name'] = cath.name
#         xformsdata['schema']['data']['use_for_self'] = "true" if QtiPackage.use_for_self else "false"
#         xformsdata['schema']['data']['use_for_control'] = "true" if QtiPackage.use_for_control else "false"
# 
#         if QtiPackage.spec_id is not None:
#             spec = specialitiesCursor(context)
#             specList = QtiPackage.spec_id.split(' ')
#             for specId in specList:
#                 spec.get(specId)
#                 xformsdata["schema"]["spec"]["item"].append({"@id": specId, "@name": spec.name})
# 
#         if QtiPackage.for_what_dev is not None:
#             dpp = cyclesCursor(context)
#             dppList = json.loads(QtiPackage.for_what_dev)["dpp"]
#             for dppId in dppList:
#                 dpp.get(dppId)
#                 xformsdata["schema"]["dpp"]["item"].append({"@id": dppId, "@name": dpp.name})
#             nmo = cycles_viewCursor(context)
#             nmoList = json.loads(QtiPackage.for_what_dev)["nmo"]
#             for nmoId in nmoList:
#                 nmo.setRange("uid", nmoId)
#                 nmo.navigate('-')
#                 xformsdata["schema"]["nmo"]["item"].append({"@id": nmoId, "@name": nmo.name})

    # Первоначальная xformssettings
    xformssettings = {  
        'properties': {  
            'event': [  
                {  
                    '@name': 'single_click',
                    '@linkId': '1',
                    'action': {
                        "#sorted": [
                            {'main_context': 'current'},
                            {'datapanel': {  
                                '@type': 'current',
                                '@tab': 'current',
                                'element': [  
                                    {  
                                        '@id': 'btzCatalogGrid',
                                        'add_context': ''
                                    },
                                    {  
                                        '@id': 'btzAttributesGrid',
                                        '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)
    session = json.loads(session)
    QtiPackage = QtiPackageCursor(context)

    if add == 'add':
        QtiPackage.PackageID = btz_card_id = unicode(uuid.uuid4())
        QtiPackage.PackageName = data_dict['schema']['data']['package_name']
        QtiPackage.EditorID = session['sessioncontext']['sid']
        QtiPackage.DateCreated = datetime.datetime.now()
        QtiPackage.Status = 'forming'
        QtiPackage.insert()
    elif add == 'edit':
        # id записи
        QtiPackage.get(session['sessioncontext']['related']['gridContext']['currentRecordId'])
        QtiPackage.PackageName = data_dict['schema']['data']['package_name']
#         QtiPackage.EditorID = session['sessioncontext']['sid']
        QtiPackage.update()

#     if data_dict['schema']['data']['authorForm']=='true':
#         if data_dict['schema']['data']['author_id'] is not None and data_dict['schema']['data']['author_id']!='':
#             eorAuthors.get(data_dict['schema']['data']['author_id'])
#             if eorAuthors.fio==data_dict['schema']['data']['author_name']:
#                 QtiPackage.extauthor = data_dict['schema']['data']['author_id']
#             else: 
#                 data_dict['schema']['data']['author_id'] = None
#         else:
#             eorAuthors.setRange("fio", data_dict['schema']['data']['author_name'])
#             if eorAuthors.tryFirst():
#                 QtiPackage.extauthor = eorAuthors.authorid
#             else:
#                 eorAuthors.authorid=uuid.uuid4()
#                 QtiPackage.extauthor = eorAuthors.authorid
#                 eorAuthors.fio=data_dict['schema']['data']['author_name']
#                 eorAuthors.email=data_dict['schema']['data']['e-mail']
#                 eorAuthors.insert()
#         QtiPackage.author= None
                    

                
#     if data_dict['schema']['data']['authorForm']=='false':
#         QtiPackage.author = data_dict['schema']['data']['author_id']
#         QtiPackage.extauthor= None
#     
#     QtiPackage.cath_id = data_dict['schema']['data']['cath_id']
#     QtiPackage.use_for_self = data_dict['schema']['data']['use_for_self'] == "true"
#     QtiPackage.use_for_control = data_dict['schema']['data']['use_for_control'] == "true"
# 
#     forWhatDev = {"nmo":[], "dpp":[]}
#     if data_dict['schema']["dpp"] == '' or data_dict['schema']["dpp"] == [] or data_dict['schema']["dpp"] == {} or\
#             data_dict['schema']["dpp"]["item"] == '' or data_dict['schema']["dpp"]["item"] == [] or data_dict['schema']["dpp"]["item"] == {}:
#         forWhatDev["dpp"] = []
#     else:
#         dppList = data_dict['schema']["dpp"]["item"] if isinstance(data_dict['schema']["dpp"]["item"], list) else [data_dict['schema']["dpp"]["item"]]
#         list1 = []
#         for ans in dppList:
#             list1.append(ans["@id"])
#         forWhatDev["dpp"] = list1
#     if data_dict['schema']["nmo"] == '' or data_dict['schema']["nmo"] == [] or data_dict['schema']["nmo"] == {} or \
#             data_dict['schema']["nmo"]["item"] == '' or data_dict['schema']["nmo"]["item"] == [] or data_dict['schema']["nmo"]["item"] == {}:
#         forWhatDev["nmo"] = []
#     else:
#         nmoList = data_dict['schema']["nmo"]["item"] if isinstance(data_dict['schema']["nmo"]["item"], list) else [data_dict['schema']["nmo"]["item"]]
#         list1 = []
#         for ans in nmoList:
#             list1.append(ans["@id"])
#         forWhatDev["nmo"] = list1
#     QtiPackage.for_what_dev = json.dumps(forWhatDev)
# 
#     if data_dict['schema']["spec"] == '' or data_dict['schema']["spec"] == [] or data_dict['schema']["spec"] == {} or \
#             data_dict['schema']["spec"]["item"] == '' or data_dict['schema']["spec"]["item"] == [] or data_dict['schema']["spec"]["item"] == {}:
#         QtiPackage.spec_id = None
#     else:
#         dppList = data_dict['schema']["dpp"]["item"] if isinstance(data_dict['schema']["dpp"]["item"], list) else [data_dict['schema']["dpp"]["item"]]
#         specList = data_dict['schema']["spec"]["item"] if isinstance(data_dict['schema']["spec"]["item"], list) else [data_dict['schema']["spec"]["item"]]
#         specRes = " ".join(unicode(n["@id"]) for n in specList)
#         QtiPackage.spec_id = specRes
# 
#     if add == 'add':
#         QtiPackage.insert()
#     else:
#         QtiPackage.update()
# 
#     # пишем доп параметры в атрибуты
#     QtiPackageAttribute = QtiPackageAttributeCursor(context)
#     QtiPackageAttribute.setRange('PackageID', QtiPackage.PackageID)
#     QtiPackageAttribute.setFilter('AttributeName', "@%'mail'%")
#     if QtiPackageAttribute.tryFirst():
#         QtiPackageAttribute.AttributeValue = data_dict['schema']['data']['e-mail']
#         QtiPackageAttribute.update()
#     else:
#         QtiPackageAttribute.AttributeID = uuid.uuid4()
#         QtiPackageAttribute.AttributeName = 'E-mail'
#         QtiPackageAttribute.AttributeValue = data_dict['schema']['data']['e-mail']
#         QtiPackageAttribute.PackageID = QtiPackage.PackageID
#         QtiPackageAttribute.insert()
#     QtiPackageAttribute.setFilter('AttributeName', u"@%'телефон'%")
#     if QtiPackageAttribute.tryFirst():
#         QtiPackageAttribute.AttributeValue = data_dict['schema']['data']['phone']
#         QtiPackageAttribute.update()
#     else:
#         QtiPackageAttribute.AttributeID = uuid.uuid4()
#         QtiPackageAttribute.AttributeName = u'Телефон'
#         QtiPackageAttribute.AttributeValue = data_dict['schema']['data']['phone']
#         QtiPackageAttribute.PackageID = QtiPackage.PackageID
#         QtiPackageAttribute.insert()
#     QtiPackageAttribute.setFilter('AttributeName', u"@%'год'%&%'составл'%")
#     if QtiPackageAttribute.tryFirst():
#         QtiPackageAttribute.AttributeValue = data_dict['schema']['data']['year']
#         QtiPackageAttribute.update()
#     else:
#         QtiPackageAttribute.AttributeID = uuid.uuid4()
#         QtiPackageAttribute.AttributeName = u'Учебный год составления'
#         QtiPackageAttribute.AttributeValue = data_dict['schema']['data']['year']
#         QtiPackageAttribute.PackageID = QtiPackage.PackageID
#         QtiPackageAttribute.insert()
    
