# coding: utf-8

import json
from uuid import uuid4
from ru.curs.celesta.showcase.utils import XMLJSONConverter
try:
    from org.apache.commons.lang3.StringEscapeUtils import unescapeHtml4
except:
    pass
try:
    from ru.curs.showcase.core.jython import JythonDTO
    from ru.curs.showcase.app.api import MessageType, UserMessage
except:
    from ru.curs.celesta.showcase import JythonDTO
    
from author._author_orm import eor_practicalCursor


def cardData(context, main=None, add=None, filterinfo=None, session=None, elementId=None):
    u'''Карточка работы с лекцией'''
    try:
        practical_id = json.loads(session)['sessioncontext']['related']['gridContext']['currentRecordId']
    except:
        practical_id = None
    practical_name = None
    practical_desc = None
    
    if add == 'edit':
        practicalCur = eor_practicalCursor(context)
        if practicalCur.tryGet(practical_id):
            practical_name = practicalCur.practical_name
            practical_desc = practicalCur.practical_descr
        practicalCur.close()
        
    xformsdata = {"schema": {
                    "@xmlns": "",
                    "practical": {
                        "context": add,
                        "id": practical_id, 
                        "name": practical_name,
                        "desc": unescapeHtml4(practical_desc) if practical_desc else ''}}}
  
    xformssettings = {
        'properties': {
            'event': [
                {'@name': 'single_click',
                 '@linkId': '1',
                 'action': {
                    '@keep_user_settings': 'false',
                    '#sorted': [
                        {'main_context': 'current'},
                        {'datapanel': {
                            '@type': 'current',
                            '@tab': 'current',
                            'element': {
                                '@id': 'practicalGrid',
                                'add_context': ''}}}]}},
                {'@name': 'single_click',
                 '@linkId': '2',
                 'action': {
                    '@keep_user_settings': 'true',
                    '#sorted': [
                        {'main_context': 'current'},
                        {'datapanel': {
                            '@type': 'current',
                            '@tab': 'current',
                            'element': {
                                '@id': 'practicalGrid',
                                '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):    
    practical_data = json.loads(xformsdata)['schema']['practical']
    pr_action = practical_data['context']    
    practicalCur = eor_practicalCursor(context)
    
    if pr_action == 'add':
        practicalCur.practical_id = unicode(uuid4())
        practicalCur.practical_name = practical_data['name']
        practicalCur.practical_descr = practical_data['desc']
        practicalCur.insert()        
    elif pr_action == 'edit':
        practical_id = practical_data['id']
        if practicalCur.tryGet(practical_id):
            practicalCur.practical_name = practical_data['name']
            practicalCur.practical_descr = practical_data['desc']
            practicalCur.update()
    elif pr_action == 'delete':
        practical_id = practical_data['id']
        if practicalCur.tryGet(practical_id):
            practicalCur.delete()
    
    practicalCur.close()
    

def html2Edit(context, main, add, filterinfo, session, elementId):
    jsonData = json.loads(filterinfo)
    html = jsonData['schema']['filter']['desc']

    data = html.replace('&lt;', '<').replace('&gt;', '>').replace('&lt', '<').replace('&gt', '>').replace('&nbsp;', ' ').replace('&nbsp', ' ')
    try:
        minidom.parseString(data)
    except:
        data = "<div>%s</div>" % data
    settings = u'''<properties></properties>'''
    res = JythonDTO(data, settings)
    return res


def htmlData(context, main=None, add=None, filterinfo=None, session=None, elementId=None):
    u'''Карточка HTML подсказки'''
    try:
        practical_id = json.loads(session)['sessioncontext']['related']['gridContext']['currentRecordId']
    except:
        practical_id = None
    
    practicalCur = eor_practicalCursor(context)
    
    htmlText = None
    if practicalCur.tryGet(practical_id):
        htmlText = practicalCur.practical_descr
        
    practicalCur.close()
        
    xformsdata = {"schema": {
            "@xmlns": "",
            "htmlText": unescapeHtml4(htmlText) if htmlText else u""}}

    xformssettings = {"properties": {}}

    return JythonDTO((XMLJSONConverter.jsonToXml(json.dumps(xformsdata))),
                     XMLJSONConverter.jsonToXml(json.dumps(xformssettings)))    
