# coding: utf-8
u'''
Основной грид реестра комлексных ДПП.

'''

import json

from com.jayway.jsonpath import JsonPath
from common.sysfunctions import toHexForXml, getGridHeight, tableCursorImport
from ru.curs.celesta.showcase.utils import XMLJSONConverter
from security.functions import userHasPermission
from umk._umk_orm import vw_cprogram_attributeCursor


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

def gridData(context, main, add=None, filterinfo=None, session=None, elementId=None,
             sortColumnList=None, firstrecord=None, pagesize=None):

    vw_cprogram_attribute = vw_cprogram_attributeCursor(context)
    cp_id = JsonPath.read(session, "$.sessioncontext.related.gridContext.currentRecordId")
    vw_cprogram_attribute.setRange('complex_program_id', cp_id)

    # Заголовки
    _header = {
        'uid': ['~~id', 'uid'],
        'attribute_name': [u'Наименование', 'attribute_name'],
        'attribute_value': [u'Значение', 'attribute_value'],
        'required': [u'Обязательный', 'required'],
        'properties': [u'properties', 'properties']
    }
    for column in _header:
        _header[column].append(toHexForXml(_header[column][0]))

    vw_cprogram_attribute.orderBy('sort')
    vw_cprogram_attribute.limit(firstrecord - 1, pagesize)

    grid_data = {
        'records': {
            'rec':[]
        }
    }
    for row in vw_cprogram_attribute.iterate():
        currentrow = {}
        currentrow[_header['uid'][2]] = row.uid
        currentrow[_header['attribute_name'][2]] = row.attribute_name
        currentrow[_header['attribute_value'][2]] = row.attribute_value
        # определяем значение в зависимости от типа
        try:
            value_type = json.loads(row.value_type)
            # string, integer, decimal, boolean, date, datetime, selector, multiselector
            if value_type['type'] == 'multiselector':
                vals = row.attribute_value.split(",")
                shows = ''
                cur = tableCursorImport(value_type['grain'], value_type['table'])(context)
                values = []
                for x in vals:
                    cur.get(x)
                    item_name = getattr(cur, value_type['name_field'])
                    # дополнительные поля - как в селекторе
                    if 'name_add_fields' in value_type:
                        if isinstance(value_type['name_add_fields'], list):
                            for y in value_type['name_add_fields']:
                                if hasattr(cur, y):
                                    item_name = u'%s - %s' % (item_name, unicode(getattr(cur, y)))
                        elif isinstance(value_type['name_add_fields'], unicode):
                            if hasattr(cur, value_type['name_add_fields']):
                                item_name = u'%s - %s' % (item_name, unicode(getattr(cur, value_type['name_add_fields'])))
                    values.append({'item': {'@id': x, "@name": item_name}})
                    shows = u'%s,%s' % (shows, item_name) if shows != '' else item_name
                # строка, которая будет отображаться
                currentrow[_header['attribute_value'][2]] = shows
            if value_type['type'] == 'selector':
                cur = tableCursorImport(value_type['grain'], value_type['table'])(context)
                cur.get(row.attribute_value)
                currentrow[_header['attribute_value'][2]] = getattr(cur, value_type['name_field'])
            if value_type['type'] == 'boolean':
                if 'true' in value_type and value_type['true'] == row.attribute_value:
                    currentrow[_header['attribute_value'][2]] = u'Да'
                elif 'false' in value_type and value_type['false'] == row.attribute_value:
                    currentrow[_header['attribute_value'][2]] = u'Нет'
            if value_type['type'] == 'select1':
                values = value_type['setValues']
                currentrow[_header['attribute_value'][2]] = values[row.attribute_value]
        except:
            pass
        currentrow[_header['required'][2]] = 'Да' if row.required else 'Нет'

        currentrow[_header['properties'][2]] = {
            'event': {
                '@name': 'row_single_click',
                'action': {
                    '#sorted': [
                        {
                            'main_context': 'current'
                        },
                        {
                            'datapanel': {
                                '@type': 'current',
                                '@tab': 'current'
                            }
                        }
                    ]
                }
            }
        }
        grid_data['records']['rec'].append(currentrow)

    return JythonDTO(XMLJSONConverter.jsonToXml(json.dumps(grid_data)),
                     None)

def gridMeta(context, main=None, add=None, filterinfo=None, session=None, elementId=None,
             sortColumnList=None):

    vw_cprogram_attribute = vw_cprogram_attributeCursor(context)
    cp_id = JsonPath.read(session, "$.sessioncontext.related.gridContext.currentRecordId")
    vw_cprogram_attribute.setRange('complex_program_id', cp_id)

    # Заголовки
    _header = {
        'uid': ['~~id', 'uid'],
        'attribute_name': [u'Наименование', 'attribute_name'],
        'attribute_value': [u'Значение', 'attribute_value'],
        'required': [u'Обязательный', 'required'],
        'properties': [u'properties', 'properties']
    }
    for column in _header:
        _header[column].append(toHexForXml(_header[column][0]))

    grid_settings = {}
    grid_settings['gridsettings'] = {
        'labels': {
            'header': 'Атрибуты КДПП'
        },
        'columns': {
            'col': []
        },
        'properties': {
            '@pagesize': 25,
            '@gridWidth': '100%',
            '@gridHeight': getGridHeight(session, numberOfGrids=2, delta=245),
            '@totalCount': vw_cprogram_attribute.count(),
            '@profile': 'default.properties'
        },
    }
    # Добавляем поля для отображения в gridsettingss
    grid_settings['gridsettings']['columns']['col'].append({'@id': _header['required'][0], '@width': "70px"})
    grid_settings['gridsettings']['columns']['col'].append({'@id': _header['attribute_name'][0]})
    grid_settings['gridsettings']['columns']['col'].append({'@id': _header['attribute_value'][0]})

    return JythonDTO(None,
                     XMLJSONConverter.jsonToXml(json.dumps(grid_settings)))

def gridToolBar(context, main=None, add=None, filterinfo=None, session=None, elementId=None):

    session_json = json.loads(session)['sessioncontext']
    string_bool = lambda x: x and 'true' or 'false'
    attr_id = JsonPath.read(session, "$.sessioncontext.related.gridContext[?(@.id=='complexProgramAttributeGrid')].currentRecordId")

    # добавление
    if userHasPermission(context, session_json['sid'], 'addComplexProgramAttribute'):
        add_style = string_bool(False)
    else:
        add_style = string_bool(True)
    # редактирование
    if userHasPermission(context, session_json['sid'], 'editComplexProgramAttribute'):
        edit_style = (string_bool(False) if attr_id
                      else string_bool(True))
    else:
        edit_style = string_bool(True)
    # удаление
    if userHasPermission(context, session_json['sid'], 'delComplexProgramAttribute'):
        delete_style = (string_bool(False) if attr_id
                      else string_bool(True))
    else:
        delete_style = string_bool(True)

    grid_toolbar = {
        'gridtoolbar': {
            '#sorted': [
                {
                    'item': {
                        '@text': u'Добавить',
                        '@hint': u'Добавить атрибут КДПП',
                        '@disable': add_style,
                        'action': {
                            '@show_in': 'MODAL_WINDOW',
                            '#sorted': [
                                {
                                    'main_context': 'current'
                                },
                                {
                                    'modalwindow': {
                                        '@caption': u'Добавить',
                                        '@height': '500',
                                        '@width': '700'
                                    }
                                },
                                {
                                    'datapanel': {
                                        '@type': 'current',
                                        '@tab': 'current',
                                        'element': {
                                            '@id': 'complexProgramAttributeCard',
                                            'add_context': 'add'
                                        }
                                    }
                                }
                            ]
                        }
                    }
                },
                {
                    'item': {
                        '@text': u'Редактировать',
                        '@hint': u'Редактировать атрибут КДПП',
                        '@disable': edit_style,
                        'action': {
                            '@show_in': 'MODAL_WINDOW',
                            '#sorted': [
                                {
                                    'main_context': 'current'
                                },
                                {
                                    'modalwindow': {
                                        '@caption': u'Редактировать',
                                        '@height': '500',
                                        '@width': '700'
                                    }
                                },
                                {
                                    'datapanel': {
                                        '@type': 'current',
                                        '@tab': 'current',
                                        'element': {
                                            '@id': 'complexProgramAttributeCard',
                                            'add_context': 'edit'
                                        }
                                    }
                                }
                            ]
                        }
                    }
                },
                {
                    'item': {
                        '@text': u'Удалить',
                        '@hint': u'Удалить атрибут КДПП',
                        '@disable': delete_style,
                        'action': {
                            '@show_in': 'MODAL_WINDOW',
                            '#sorted': [
                                {
                                    'main_context': 'current'
                                },
                                {
                                    'modalwindow': {
                                        '@caption': 'Удалить',
                                        '@height': '140',
                                        '@width': '400'
                                    }
                                },
                                {
                                    'datapanel': {
                                        '@type': 'current',
                                        '@tab': 'current',
                                        'element': {
                                            '@id': 'complexProgramAttributeDeleteCard',
                                            'add_context': ''
                                        }
                                    }
                                }
                            ]
                        }
                    }
                }
            ]
        }
    }

    return XMLJSONConverter.jsonToXml(json.dumps(grid_toolbar))