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

@author: v.popov
'''
import json
from ru.curs.celesta.showcase.utils import XMLJSONConverter
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.celesta.showcase import UserMessage
    from ru.curs.celesta.showcase import MessageType
except:
    from ru.curs.celesta.showcase import JythonDTO
from qt._qt_orm import QtiPackageCursor
from security.functions import userHasPermission


def cardData(context, main=None, add=None, filterinfo=None, session=None, elementId=None):
    u'''Данные для карточки.'''
    eor_id = json.loads(session)['sessioncontext']['related']['gridContext']['currentRecordId']
    # в зависимости от элемента берем разные курсоры
    QtiPackage = QtiPackageCursor(context)
    QtiPackage.get(eor_id)
    oldstatus = QtiPackage.Status
    grid_id = 'btzCatalogGrid'
    # Структура данных
    xformsdata = {"schema": {
                    "@xmlns":"",
                    "data": {
                        "eor_id": eor_id,
                        "oldstatus": oldstatus,
                        "newstatus": oldstatus}}}

    # действия в зависимости от статуса
    xformsdata['schema']['data']['actions'] = []
    xformsdata['schema']['data']['actions'].append({'@label': u'Оставить в текущем статусе',
                                                     '@value': oldstatus})
    if oldstatus == u'forming':
        xformsdata['schema']['data']['actions'].append({'@label': u'Сформировать',
                                                     '@value': u'ready'})
        xformsdata['schema']['data']['newstatus'] = u'ready'
    elif oldstatus == u'':
        xformsdata['schema']['data']['actions'].append({'@label': u'Сформировать',
                                                     '@value': u'ready'})
        xformsdata['schema']['data']['newstatus'] = u'ready'
    elif oldstatus == u'ready':
        xformsdata['schema']['data']['actions'].append({'@label': u'Вернуть в статус "Формируется"',
                                                     '@value': u'forming'})
        if userHasPermission(context, json.loads(session)['sessioncontext']['sid'], 'addEorToArchive'):
            xformsdata['schema']['data']['actions'].append({'@label': u'Отправить в архив',
                                                     '@value': u'archive'})
            xformsdata['schema']['data']['newstatus'] = u'archive'
    elif oldstatus == u'archive':
        xformsdata['schema']['data']['actions'].append({'@label': u'Вернуть в статус "Формируется"',
                                                     '@value': u'forming'})
        xformsdata['schema']['data']['actions'].append({'@label': u'Вернуть в статус "Сформирован"',
                                                     '@value': u'ready'})


    # Первоначальная 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":grid_id,
                                                                                 "add_context": ""
                                                                                 }
                                                                     }
                                                      }]}
                                             },
                                             {"@name":"single_click",
                                             "@linkId": "2",
                                             "action":{
                                                  "@keep_user_settings": "true",
                                                  "#sorted": [
                                                      {"main_context": "current"},
                                                      {"datapanel": {"@type": "current",
                                                                     "@tab": "current"
                                                                                        ,
                                                                     "element": {"@id":grid_id,
                                                                                 "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)
    # статус должен измениться
    if data_dict['schema']['data']['newstatus'] != data_dict['schema']['data']['oldstatus']:

        QtiPackage = QtiPackageCursor(context)
        QtiPackage.get(data_dict['schema']['data']['eor_id'])
        QtiPackage.Status = data_dict['schema']['data']['newstatus']
        QtiPackage.update()
