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

@author: v.popov
'''

import simplejson as json
from qt._qt_orm import QtiPackageCursor, QtiThemeCursor, \
    QtiPackageAttributeCursor, QtiQuestionCursor
import uuid



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
    from ru.curs.showcase.app.api import UserMessage, MessageType
except:
    from ru.curs.celesta.showcase import JythonDTO, ResultSelectorData, DataRecord, UserMessage, MessageType

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



def cardData(context, main=None, add=None, filterinfo=None, session=None, elementId=None):
    u'''Данные для карточки.'''
    
    session = json.loads(session)
    QtiTheme = QtiThemeCursor(context)
    
    urlparams = session['sessioncontext']['urlparams']['urlparam']
    
    for urlparam in urlparams:
        if urlparam["@name"] == "package":
            package_id = urlparam["@value"][0]
            
    # Структура данных
    xformsdata = {"schema":
                  {"@xmlns":"",
                    "data":
                        {
                        "package_id": package_id,
                        "theme": []
                         }

                    }
                  }
                  
    QtiTheme.setRange('PackageID', package_id)
    QtiTheme.orderBy('ThemeOrder')


    for QtiTheme in QtiTheme.iterate():
        xformsdata['schema']['data']['theme'].append({'id': QtiTheme.ThemeID,
                                                       'name': QtiTheme.ThemeName,
                                                       'order': QtiTheme.ThemeOrder})


    # Первоначальная xformssettings
    xformssettings = {"properties":{"event":[{"@name":"single_click",
                                             "@linkId": "1",
                                             "action":{
                                                  "@keep_user_settings": "false",
                                                  "#sorted": [
                                                      {"main_context": "current"},
                                                      {"navigator": {"@refresh": "true"}},
                                                      {"datapanel": {"@type": "current",
                                                                     "@tab": "current",
                                                                     "element": {"@id":'webThemeGrid',
                                                                                 "add_context": ""
                                                                                 }
                                                                     }
                                                      }]}
                                             },
                                             {"@name":"single_click",
                                             "@linkId": "2",
                                             "action":{
                                                  "@keep_user_settings": "true",
                                                  "#sorted": [
                                                      {"main_context": "current"},
                                                      {"datapanel": {"@type": "current",
                                                                     "@tab": "current",
                                                                     "element": {"@id":'webThemeGrid',
                                                                                 "add_context": ""
                                                                                 }
                                                                     }
                                                      }]}
                                             }]
                                    }
                      }


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


def cardDataSave(context, main=None, add=None, filterinfo=None, session=None, elementId=None, xformsdata=None):
    u'''Сохранение карточки. '''

    data_dict = json.loads(xformsdata)
    QtiTheme = QtiThemeCursor(context)
    qti_question = QtiQuestionCursor(context)
    #
    package_id = data_dict['schema']['data']['package_id']
    if 'theme' in data_dict['schema']['data']:
        themes = data_dict['schema']['data']['theme']
    else:
        themes = []
    # raise Exception(themes)
    if isinstance(themes, dict):
        themes = [data_dict['schema']['data']['theme']]
    # добавляем - обновляем темы
    for theme in themes:
        if theme['id'] == u'new':
            QtiTheme.ThemeID = unicode(uuid.uuid4())
            QtiTheme.ThemeName = theme['name']
            QtiTheme.ThemeOrder = theme['order']
            QtiTheme.PackageID = package_id
            QtiTheme.insert()
        else:
            QtiTheme.get(theme['id'])
            QtiTheme.ThemeName = theme['name']
            QtiTheme.ThemeOrder = theme['order']
            QtiTheme.update()
        # context.message(QtiTheme.asCSVLine())
    # удаляем темы, по которым нет вопросов из тем
    old_theme_ids = [k['id'] for k in themes if k['id'] != '']

    old_theme_has_q = False
    QtiTheme.clear()
    QtiTheme.setRange('PackageID', package_id)
    if len(old_theme_ids) < QtiTheme.count():
        for QtiTheme in QtiTheme.iterate():
            if QtiTheme.ThemeID not in old_theme_ids:
                qti_question.clear()
                qti_question.setRange('ThemeID', QtiTheme.ThemeID)
                if qti_question.count() == 0:
                    QtiTheme.delete()
                else:
                    old_theme_has_q = True
                    break

    if old_theme_has_q:
        context.message(u'По удаленным темам есть вопросы, удалить не удалось.')


def check_numbers_theme(context, main=None, add=None, filterinfo=None, session=None, data=None):
    
    dataDict = json.loads(data)['schema']['data']['theme']
    
    if not isinstance(dataDict,list):
        dataDict = [dataDict]
    
    return_data = {
        'schema': { 
            '@not_unique': ''
        }
    }               
    if len(dataDict) != len(set(x['order'] for x in dataDict)):
        return_data['schema']['@not_unique'] = u'Значения некоторых номеров не уникальны!'
        
    return XMLJSONConverter.jsonToXml(json.dumps(return_data))
