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

@author: m.prudyvus

Карточка аккредитационного центра
'''
import json
import uuid

from com.jayway.jsonpath import JsonPath
from fias.xforms.addressSearch import addressSearchDict, saveAdress, \
    addressEditDict
from nci._nci_orm import accred_centerCursor, org_addressCursor
from ru.curs.celesta.showcase.utils import XMLJSONConverter


try:
    from ru.curs.showcase.core.jython import JythonDTO
except:
    from ru.curs.celesta.showcase import JythonDTO



def cardData(context, main=None, add=None, filterinfo=None, session=None, elementId=None):
    u'''Карточка аккредитационных центров'''

    accred_center = accred_centerCursor(context)
    org_address = org_addressCursor(context)

    if add == 'edit':
        curr_rec = JsonPath.read(session, "$.sessioncontext.related.gridContext.currentRecordId")
        accred_center.get(curr_rec)

    if not accred_center.address_id:
        address = addressSearchDict().get('address')
    else:
        org_address.get(accred_center.address_id)
        address = addressEditDict(context, org_address).get("address")


    xformsdata = {"schema": {"@xmlns": "",
                             "record": {"uid": accred_center.uid,
                                        "type": accred_center.type,
                                        "website": accred_center.website,
                                        "phone": accred_center.phone,
                                        "email": accred_center.email},
                             "types": {"type": [{"@value": "region",
                                                 "@label": "Региональный"},
                                                {"@value": "federal",
                                                 "@label": "Федеральный"}, ]},
                             "address": address
                             }
                  }

    xformssettings = {"properties":{"event":[{"@name":"single_click",
                                              "@linkId": "1",
                                              "action":{"@keep_user_settings": "true",
                                                      '#sorted': [
                                                          {"main_context": "current"},
                                                          {"datapanel": {"@type": "current",
                                                                      "@tab": "current",
                                                                      "element": {"@id":"accredCenterGrid",
                                                                                  "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'''Сохранение данных о ФЛ. '''

    accred_center = accred_centerCursor(context)
    org_address = org_addressCursor(context)

    data_dict = json.loads(xformsdata)["schema"]

    if data_dict["record"]["uid"]:
        # Редактирование уже существующей
        accred_center.get(data_dict["record"]["uid"])
    else:
        # Добавление новой записи в person
        accred_center.uid = uuid.uuid4()

    if not accred_center.address_id:
        org_address.address_id = uuid.uuid4()
    else:
        org_address.get(accred_center.address_id)

    for field in ("type", "website", "phone", "email"):
        accred_center.__setattr__(field, data_dict["record"][field] or None)

    saveAdress(org_address, data_dict["address"])

    if not accred_center.address_id:
        accred_center.address_id = org_address.address_id

        org_address.insert()
    else:
        org_address.update()
    if add == 'add':

        accred_center.insert()
    else:
        accred_center.update()


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

    # Структура данных
    xforms_data = {'schema': {'@xmlns': '',
                              'data': {'form_text': 'Вы действительно хотите удалить данные об аккредитационном центре?'
                                       }
                              }
                   }

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

    return JythonDTO(XMLJSONConverter.jsonToXml(json.dumps(xforms_data)),
                     XMLJSONConverter.jsonToXml(json.dumps(xforms_settings)))


def deleteCardSave(context, main=None, add=None, filterinfo=None, session=None, elementId=None, xformsdata=None):
    u'''Удаление записи'''
    accred_center = accred_centerCursor(context)
    org_address = org_addressCursor(context)

    curr_rec = JsonPath.read(session, "$.sessioncontext.related.gridContext.currentRecordId")
    accred_center.get(curr_rec)
    accred_center.delete()

    if org_address.tryGet(accred_center.address_id):
        org_address.delete()