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

@author: 
'''
import json

from ru.curs.celesta.showcase.utils import XMLJSONConverter
from common.sysfunctions import toHexForXml
from common.sysfunctions import getGridHeight

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 gridData(context, main=None, add=None, filterinfo=None,
             session=None, elementId=None, sortColumnList=None, firstrecord=None, pagesize=None):
    u'''Функция получения данных для грида. '''
    
    practicalCur = eor_practicalCursor(context)    
    
    try:
        extfilter = session['sessioncontext']['related']['xformsContext']['formData']['schema']['data']['name']
    except:
        extfilter = None
        
    practicalCur.orderBy('practical_name')    
    if extfilter:
        practicalCur.setFilter('practical_name', "@%%'%s'%%" % (extfilter))
    
    data = {"records":{"rec":[]}}

    _headers = {'id': ["~~id"],
                'name': [u'Название практического занятия'],
                "properties": ["properties"]}
       
    for column in _headers:
        _headers[column].append(toHexForXml(_headers[column][0]))                

#     if practicalCur.count() > 0:
#         practicalCur.limit(firstrecord - 1, pagesize)
    
    for practical in practicalCur.iterate():
        practical_dict = {}
        practical_dict[_headers['id'][1]] = practical.practical_id
        practical_dict[_headers['name'][1]] = practical.practical_name
        practical_dict[_headers['properties'][1]] = {'event': {
                                                '@name': 'row_single_click',
                                                'action': {
                                                    '#sorted': [
                                                        {'main_context': 'current'},
                                                        {'datapanel': {
                                                            '@type': 'current',
                                                            '@tab': 'current',
                                                            "element": [ 
                                                                {"@id": "htmlHint",
                                                                 "add_context": ''}]}}]}}}
                
        data["records"]["rec"].append(practical_dict)
        
        
    practicalCur.close()
    
    data = XMLJSONConverter.jsonToXml(json.dumps(data))
    
    return JythonDTO(data, None)


def gridMeta(context, main, add=None, filterinfo=None, session=None, elementId=None):
    u"""Функция получения параметров для грида"""    
    session = json.loads(session)
    
    practicalCur = eor_practicalCursor(context) 
    try:
        extfilter = session['sessioncontext']['related']['xformsContext']['formData']['schema']['data']['name']
    except:
        extfilter = None
    
    if extfilter:
        practicalCur.setFilter('practical_name', "@%%'%s'%%" % (extfilter))
        
    totalcount = practicalCur.count()
    practicalCur.close()
    u"""Настройки грида"""
    settings = {}
    settings["gridsettings"] = {"columns": {"col": []},
                                "properties": {"@gridHeight": getGridHeight(session, 2),
                                               "@gridWidth": '100%',
                                               "@totalCount": totalcount,
                                               "@pagesize": "50" }}
    
    settings["gridsettings"]["columns"]["col"].append({"@id":u'Название практического занятия',"@width":"300px"})
 
    return JythonDTO(None, XMLJSONConverter.jsonToXml(json.dumps(settings)))


def gridToolBar(context, main=None, add=None, filterinfo=None, session=None, elementId=None):
    u"""Функция отображения панели инструментов"""
    ss = json.loads(session)['sessioncontext']
    style = "true"
     
    if 'currentRecordId' in ss['related']['gridContext']:
        style = 'false'
         
    data = {"gridtoolbar": {
            "item": [
                {"@text": u"Добавить",
                 "@hint": u"Добавить практическое занятие",
                 "@disable": "false",
                 "action": {
                    "@show_in":"MODAL_WINDOW",
                    "#sorted": [
                        {"main_context":'current'},
                        {"modalwindow": {
                            "@caption": u"Добавление практического занятия",
                            "@height":"280",
                            "@width":"640"}},
                        {"datapanel": {
                            "@type":"current",
                            "@tab":"current",
                            "element": {
                                "@id":'practicalCard',
                                "add_context": "add"}}}]}},
                {"@text": u"Изменить",
                 "@hint": u"Изменить параметры практического занятия",
                 "@disable": style,
                 "action":{
                    "@show_in":"MODAL_WINDOW",
                    "#sorted": [
                        {"main_context":'current'},
                        {"modalwindow": {
                            "@caption": u"Изменение практического занятия",
                            "@height":"280",
                            "@width":"640"}},
                        {"datapanel": {
                            "@type":"current",
                            "@tab":"current",
                            "element": {
                                "@id":'practicalCard',
                                "add_context": "edit"}}}]}},
                {"@text":u"Удалить",
                 "@hint":u"Удалить практическое занятие",
                 "@disable": style,
                 "action": {
                    "@show_in":"MODAL_WINDOW",
                    "#sorted": [
                        {"main_context":'current'},
                        {"modalwindow": {
                            "@caption":u"Удаление практического занятия",
                            "@height":"120",
                            "@width":"440"}},
                        {"datapanel": {
                            "@type":"current",
                            "@tab":"current",
                            "element": {
                                "@id":'practicalCard',
                                "add_context": "delete"}}}]}}]}}
        
    return XMLJSONConverter.jsonToXml(json.dumps(data))

