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

@author: a.konik

'''
from java.util import ArrayList
import json
from qt._qt_orm import *
import datetime

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

from ru.curs.celesta.showcase.utils import XMLJSONConverter

try:
    from ru.curs.showcase.core.selector import ResultSelectorData
    from ru.curs.showcase.core.jython import JythonDownloadResult
    from ru.beta2.extra.gwt.ui.selector.api import DataRecord
except:
    pass



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

    #raise Exception(main, session)
    # Курсоры
    Content_AttributeValue = Content_AttributeValueCursor(context)
    listAttributeContent = listAttributeContentCursor(context)
    listAttributeContent.setFilter("AttributeContentID", "1|2|4|5|6|8|9|10|12")
    Content = ContentCursor(context)
    # Первоначальная 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":"btzCatalogGrid",
                                                                                 "add_context": ""
                                                                                 }
                                                                     }
                                                      }]}
                                             }
                                             ]
                                    }
                      }

    contentid = json.loads(session)['sessioncontext']['related']['gridContext']['currentRecordId']
    Content.setRange('ContentID', contentid)
    if Content.tryFirst():

        xformsdata = {"schema":{"@xmlns":"",
                                "data": {"@packageid": contentid,
                                         "@contentid": Content.ContentID
                                        }
                                }
                      }

        Content_AttributeValue.setRange('ContentID', Content.ContentID)
        xformsdata["schema"]["data"]["subdata"] = []
        for number in listAttributeContent.iterate():
            attrdict = {}
            attrdict["@attrid"] = number.AttributeContentID
            attrdict["@attrname"] = number.AttributeContentDescription
            Content_AttributeValue.get(Content.ContentID, number.AttributeContentID)
            attrdict["@attrvalue"] = Content_AttributeValue.AttributeValue
            xformsdata["schema"]["data"]["subdata"].append(attrdict)

    else:
        xformsdata = {"schema":{"@xmlns":"",
                                "data": {"@contentid": contentid,
                                         "@packageid": contentid,
                                         }
                                }
                      }

        xformsdata["schema"]["data"]["subdata"] = []
        for number in listAttributeContent.iterate():
            attrdict = {}
            attrdict["@attrid"] = number.AttributeContentID
            attrdict["@attrname"] = number.AttributeContentDescription
            # заполняем значения по умолчанию
            if number.AttributeContentID == 4:
                attrdict["@attrvalue"] = '70'
            elif number.AttributeContentID == 5:
                attrdict["@attrvalue"] = '81'
            elif number.AttributeContentID == 6:
                attrdict["@attrvalue"] = '91'
            elif number.AttributeContentID == 8:
                attrdict["@attrvalue"] = '0'
            elif number.AttributeContentID == 9:
                attrdict["@attrvalue"] = '1'
            elif number.AttributeContentID == 10:
                attrdict["@attrvalue"] = '1'
            else:
                attrdict["@attrvalue"] = ''
            xformsdata["schema"]["data"]["subdata"].append(attrdict)

    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'''Функция сохранения карточки'''


    Content_AttributeValue = Content_AttributeValueCursor(context)
    Content = ContentCursor(context)
    data_dict = json.loads(xformsdata)
    contentid = data_dict["schema"]["data"]["@contentid"]
    packageid = data_dict["schema"]["data"]["@packageid"]
    Content.setRange('ContentID', contentid)
    if Content.tryFirst():
        for attrdict in data_dict["schema"]["data"]["subdata"]:
            Content_AttributeValue.tryGet(contentid, int(attrdict["@attrid"]))
            if Content_AttributeValue.AttributeValue != '':
                Content_AttributeValue.RecStatus = 'edt'
            else:
                Content_AttributeValue.RecStatus = 'add'
            Content_AttributeValue.AttributeValue = unicode(attrdict["@attrvalue"])
            Content_AttributeValue.WhenAdd = datetime.datetime.now()
            Content_AttributeValue.UserName = json.loads(session)['sessioncontext']['username']
            Content_AttributeValue.update()

    else:

        Content.ContentID = contentid
        Content.PackageID = packageid
        Content.WhenAdd = datetime.datetime.now()
        Content.ContentDate = datetime.datetime.now()
        Content.ContentName = u'Something'
        Content.TypeContentID = 1
        Content.ContentActualityNumber = 1
        Content.ContentRedactionNumber = 1
        Content.StatusContentID = 1
        Content.insert()
        for attrdict in data_dict["schema"]["data"]["subdata"]:
            Content_AttributeValue.RecStatus = 'add'
            Content_AttributeValue.AttributeContentID = int(attrdict["@attrid"])
            Content_AttributeValue.ContentID = contentid
            Content_AttributeValue.AttributeValue = unicode(attrdict["@attrvalue"])
            Content_AttributeValue.WhenAdd = datetime.datetime.now()
            Content_AttributeValue.UserName = json.loads(session)['sessioncontext']['username']
            Content_AttributeValue.insert()
