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

@author: Kuzmin M.
'''

import json
from uuid import uuid4

from common.hierarchy import getNewItemInLevelInHierarchy, generateSortValue, \
    deleteNodeFromHierarchy
from nci._nci_orm import control_form_typeCursor, education_formCursor
from ru.curs.celesta.showcase.utils import XMLJSONConverter
from umk._umk_orm import edu_contentCursor, umk_versionCursor, \
    cprogram_specializationCursor


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


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

    edu_content = edu_contentCursor(context)
    control_form_type = control_form_typeCursor(context)
    education_form = education_formCursor(context)
    umk_version = umk_versionCursor(context)
    cprogram_specialization = cprogram_specializationCursor(context)
    sessionjson = json.loads(session)["sessioncontext"]
    gridContext = sessionjson["related"]["gridContext"]
    if "umkVersionId" in context.getData():
        umk_version_id = context.getData()["umkVersionId"]
    else:
        umk_version_id = None
    umk_version.get(umk_version_id)
    # Структура данных
    xformsdata = {"schema":
                  {"@xmlns":"",
                    "data":
                        {"uid":"",
                        "complex_program_id": umk_version.complex_program_id,
                        "dewey": "",
                        "sortvalue": "",
                        "name": "",
                        "type":"",
                        "type_list":[],
                        "type_name":"",
                        "hours":"",
                        "zet":"",
                        "control_form":"",
                        'control_form_id': "",
                        "education_form": "",
                        'education_form_id': "",
                        # "chair":"",
                        # "competence_list":[],
                        # вариант по дефолту ДОЛЖЕН быть пустым. он дублирует значение type для получения возможности
                        # выбрать что добавлять Модуль или Раздел, когда мы уже встали на какой-то определенный раздел
                        "variant":'',
                        "specialization_id": "",
                        "specialization_name": ""
                         }

                    }
                  }
    # проверка на выделенную запись
    if 'currentRecordId' in gridContext:
        currentRecordId = gridContext["currentRecordId"]
    else:
        currentRecordId = ''
    if currentRecordId:
        edu_content.get(currentRecordId)

    # Типы элементов из CelestaDoc
    table_meta = edu_content.meta()
    column_name = 'type'
    typeDict = json.loads(table_meta.getColumn(column_name).getCelestaDoc())
    for value, label in typeDict.iteritems():
        type = {"value":value,
                "label":label
                }
        xformsdata['schema']['data']['type_list'].append(type)


    if add == 'add':
        # проверка на тип Элемента для добавления
        if currentRecordId:
            type = edu_content.type + 1 if edu_content.type != 5 else edu_content.type
        else:
            type = 1
    elif add == 'edit':
        type = edu_content.type
        if edu_content.hours: xformsdata['schema']['data']['hours'] = int(edu_content.hours)
        xformsdata['schema']['data']['uid'] = edu_content.uid
        xformsdata['schema']['data']['name'] = edu_content.name
        xformsdata['schema']['data']['control_form'] = control_form_type.name if control_form_type.tryGet(edu_content.control_form) else ''
        xformsdata['schema']['data']['control_form_id'] = edu_content.control_form
        xformsdata['schema']['data']['education_form'] = education_form.name if control_form_type.tryGet(edu_content.education_form) else ''
        xformsdata['schema']['data']['education_form_id'] = edu_content.education_form
        xformsdata['schema']['data']['specialization_id'] = edu_content.specialization_id if edu_content.specialization_id else ''
        if cprogram_specialization.tryGet(edu_content.specialization_id):
            xformsdata['schema']['data']['specialization_name'] = cprogram_specialization.name


    if type:
        xformsdata['schema']['data']['type'] = type
        xformsdata['schema']['data']['type_name'] = typeDict['%s' % type]
    xformsdata['schema']['data']['dewey'] = edu_content.dewey


    # Первоначальная 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":'eduContentGrid',
                                                                                 "add_context": ""
                                                                                 }
                                                                     }}]
                                                       }
                                             },
                                             {"@name":"single_click",
                                             "@linkId": "2",
                                             "action":{
                                                "@keep_user_settings": 'true',
                                                '#sorted': [
                                                    {"main_context": "current"},
                                                    {"datapanel": {"@type": "current",
                                                                     "@tab": "current",
                                                                     "element": {"@id":'eduContentGrid',
                                                                                 "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'''Сохранение карточки. '''


    edu_content = edu_contentCursor(context)
    umk_version = umk_versionCursor(context)
    xformsdata = json.loads(xformsdata)['schema']['data']
    if "umkVersionId" in context.getData():
        umk_version_id = context.getData()["umkVersionId"]
    else:
        umk_version_id = None
    umk_version.get(umk_version_id)
    edu_content.setRange('umk_version', umk_version_id)
    # генерация номера иерархии Дьюи
    if 'currentRecordId' not in json.loads(session)['sessioncontext']['related']['gridContext'] or xformsdata['variant'] == '1':
        newDeweyNumber = getNewItemInLevelInHierarchy(context, edu_content, 'dewey')
    else:
        currentRecordId = json.loads(session)['sessioncontext']['related']['gridContext']['currentRecordId']
        fullDewey = xformsdata['dewey']
        if add == 'add':
            if len(fullDewey.split('.')) == 5:
                cutDewey = fullDewey.rsplit('.', 1)[0]
                edu_content.setFilter('dewey', "('%s.'%%)&(!'%s.'%%'.'%%)" % (cutDewey, cutDewey))
                childCount = edu_content.count()
                newDeweyNumber = '%s.%d' % (cutDewey, childCount + 1)
                # raise Exception(newDeweyNumber)
            else :
                edu_content.get(currentRecordId)
                newDeweyNumber = getNewItemInLevelInHierarchy(context, edu_content, 'dewey')
            edu_content.clear()

    if add == 'add':
        eus_uid = uuid4()
        edu_content.uid = eus_uid
        edu_content.complex_program_id = umk_version.complex_program_id
        edu_content.umk_version = umk_version_id
        edu_content.dewey = newDeweyNumber
        edu_content.sortvalue = generateSortValue(newDeweyNumber)
        edu_content.type = xformsdata['type']
    else:
        eus_uid = xformsdata['uid']
        edu_content.get(eus_uid)
    edu_content.name = xformsdata['name']
    if xformsdata['hours']:
        edu_content.hours = xformsdata['hours']
    edu_content.control_form = xformsdata['control_form_id'] if xformsdata['control_form_id'] != '' else None
    edu_content.education_form = xformsdata['education_form_id'] if xformsdata['education_form_id'] != '' else None
    edu_content.specialization_id = xformsdata['specialization_id'] if xformsdata['specialization_id'] else None

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

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

    string_bool = lambda x: x and 'true' or 'false'

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

    # Первоначальная xforms_settings
    xforms_settings = {
        'properties': {
            'event': [
                {
                    '@name': 'single_click',
                    '@linkId': '1',
                    'action': {
                        '@keep_user_settings': string_bool(True),
                        '#sorted': [
                          {'main_context': 'current'},
                          {'datapanel': {
                            '@type': 'current',
                            '@tab': 'current',
                            'element': {
                                '@id': 'eduContentGrid',
                                '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'''Сохранение карточки. '''

    edu_content = edu_contentCursor(context)
    current_id = json.loads(session)['sessioncontext']['related']['gridContext']['currentRecordId']
    edu_content.get(current_id)
    deleteNodeFromHierarchy(context, edu_content, 'dewey', 'sortvalue')