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

@author: Victor B.
'''
import uuid
import json
from java.text import SimpleDateFormat
from ru.curs.celesta.showcase.utils import XMLJSONConverter
from common.sysfunctions import toHexForXml
from qt._qt_orm import QtiPackageCursor, QtiThemeCursor, QtiQuestionCursor
from author._author_orm import eor_statusesCursor
from security.functions import userHasPermission
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):
    session = json.loads(session)
    sid = session['sessioncontext']['sid']
    extfilter = ''
    if 'xformsContext' in session['sessioncontext']['related']:
        if 'formData' in session['sessioncontext']['related']['xformsContext']:
            extfilter = session['sessioncontext']['related']['xformsContext']['formData']['schema']['data']

    qti_package = QtiPackageCursor(context)
    qti_theme = QtiThemeCursor(context)
    qti_question = QtiQuestionCursor(context)
    eor_statuses = eor_statusesCursor(context)
    if extfilter != '':
        # применяем внешний фильтр
        externalFilter(context, qti_package, extfilter)

    qti_package.orderBy('DateCreated DESC')
    qti_package.limit(firstrecord - 1, pagesize)

    if userHasPermission(context, sid, 'btzEditor') and not userHasPermission(context, sid, 'btzAdmin'):
        qti_package.setRange('EditorID', sid)

    df = SimpleDateFormat("dd.MM.yyyy")

    data = {"records":{"rec":[]}}

    for rec in qti_package.iterate():
        currentrow = {}
        currentrow[toHexForXml("~~id")] = rec.PackageID
        currentrow[toHexForXml(u"Название")] = rec.PackageName
        currentrow[toHexForXml(u"Дата создания")] = df.format(rec.DateCreated) if rec.DateCreated is not None else ''
        if eor_statuses.tryGet(rec.Status):
            currentrow[toHexForXml(u"Статус")] = eor_statuses.name
        else:
            currentrow[toHexForXml(u"Статус")] = rec.Status
        count = 0
        qti_theme.setRange('PackageID', rec.PackageID)
        for qti_theme in qti_theme.iterate():
            qti_question.setRange('ThemeID', qti_theme.ThemeID)
            count += qti_question.count()
        currentrow[toHexForXml(u'Кол-во ТЗ')] = count
        currentrow["properties"] = {"event": {
                                        "@name":"row_single_click",
                                        "action": {
                                          "#sorted": [
                                              {"main_context":"current"},
                                              {"datapanel":
                                                 {"@type":"current",
                                                  "@tab":"current",
                                                  "element": [
                                                    {'@id': 'btzAttributesGrid',
                                                    "add_context": ''},]}}]}}}
        data['records']['rec'].append(currentrow)

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


def gridMeta(context, main=None, add=None, filterinfo=None, session=None, elementId=None, sortColumnList=None):
    extfilter = ''
    session = json.loads(session)
    sid = session['sessioncontext']['sid']
    if 'xformsContext' in session['sessioncontext']['related']:
        if 'formData' in session['sessioncontext']['related']['xformsContext']:
            extfilter = session['sessioncontext']['related']['xformsContext']['formData']['schema']['data']

    qti_package = QtiPackageCursor(context)
    if extfilter != '':
        # применяем внешний фильтр
        externalFilter(context, qti_package, extfilter)
    if userHasPermission(context, sid, 'btzEditor') and not userHasPermission(context, sid, 'btzAdmin'):
        qti_package.setRange('EditorID', sid)

    dpheight = session['sessioncontext']['currentDatapanelHeight']
    totalCount = qti_package.count()
    meta = {"gridsettings": {
                "labels": {
                    "header": {
                        "b":u"Банки тестовых заданий"}},
                     "columns": {
                        "col": [
                            {"@id":u'Название'},
                            {"@id":u'Дата создания'},
                            {"@id":u'Статус'}]},
                     "properties": {
                        "@flip": "false",
                        "@pagesize": 100,
                        "@totalCount": totalCount,
                        "@gridWidth": "100%",
                        "@gridHeight": int(int(dpheight) * 0.35),
                        "@profile":"default.properties"}}}

    meta["gridsettings"]["columns"]["col"].append({"@id":"Кол-во ТЗ", "@width": "80px"})
    return JythonDTO(None, XMLJSONConverter.jsonToXml(json.dumps(meta)))


def gridToolBar(context, main=None, add=None, filterinfo=None, session=None, elementId=None):
    sessionjson = json.loads(session)
    add_style = "false"
    del_style = "true"
    change_status_style = "true"
    copystyle = "true"
    editstyle = "true"
    downLoadStyle = "true"
    
    qti_package = QtiPackageCursor(context)
    if "gridContext" in sessionjson["sessioncontext"]["related"] \
    and 'currentRecordId' in sessionjson["sessioncontext"]["related"]["gridContext"]:
        package_id = sessionjson["sessioncontext"]["related"]["gridContext"]['currentRecordId']
        qti_package.get(package_id)
        editstyle = 'false'
        downLoadStyle = 'false'
        del_style = 'false'
        change_status_style = 'false'
        if qti_package.Status == u'ready':
            copystyle = "false"
    else:
        package_id = ''

    data = {"gridtoolbar":  {
                "#sorted": [
                  {"group":  {
                      "@text": u"БТЗ",
                    "#sorted": [  
                        {"item": {
                            "@text": u"Добавить",
                             "@hint": u"Добавить БТЗ",
                             "@disable": add_style,
                             "action": {
                                "@show_in": "MODAL_WINDOW",
                                "#sorted": [
                                    {"main_context": 'current'},
                                    {"modalwindow": {
                                        "@caption": "Добавление БТЗ",
                                        "@height": "500",
                                        "@width": "800"}},
                                     {"datapanel": {
                                        "@type":"current",
                                        "@tab":"current",
                                        "element": {
                                            "@id":'addBtzCard',
                                            "add_context": "add"}}}]}}},
                        {"item": {
                            "@text":u"Редактировать",
                            "@hint":u"Редактировать БТЗ",
                            "@disable": editstyle,
                            "action": {
                                "@show_in":"MODAL_WINDOW",
                                "#sorted": [
                                    {"main_context":'current'},
                                    {"modalwindow": {
                                        "@caption":"Редактирование БТЗ",
                                        "@height":"500",
                                        "@width":"800"}},
                                    {"datapanel": {
                                        "@type":"current",
                                        "@tab":"current",
                                        "element": {
                                            "@id":'addBtzCard',
                                            "add_context": "edit"}}}]}}},
                        {"item": {
                            "@text":u"Удалить",
                            "@hint":u"Удалить БТЗ",
                            "@disable":del_style,
                            "action": {
                                "@show_in":"MODAL_WINDOW",
                                "#sorted": [
                                    {"main_context":'current'},
                                    {"modalwindow": {
                                        "@caption":"Удаление БТЗ",
                                        "@height":"250",
                                        "@width":"400"}},
                                     {"datapanel":
                                        {"@type":"current",
                                         "@tab":"current",
                                         "element":
                                             {"@id":'delBtzCard',
                                              "add_context": ""}
                                        }
                                     }]
                                 }
                             }
    
                           },
                         {"separator": {}},
                         {"item":
                            {"@text":u"Изменить статус",
        #                    "@img":"bad.png",
                             "@hint":u"Изменить статус БТЗ",
                             "@disable":change_status_style,
                             "action":
                                 {"@show_in":"MODAL_WINDOW",
                                  "#sorted":
                                    [{"main_context":'current'},
                                     {"modalwindow":
                                        {"@caption":"Изменение статуса",
                                         "@height":"130",
                                         "@width":"440"
                                         }
                                      },
                                     {"datapanel":
                                        {"@type":"current",
                                         "@tab":"current",
                                         "element":
                                             {"@id":'changeBtzStatusCard',
                                              "add_context": ""}
                                        }
                                     }]
                                 }
                             }
    
                           },
                        {"item":
                            {"@text":u"Создать копию",
        #                    "@img":"bad.png",
                             "@hint":u"Создать копию БТЗ",
                             "@disable":copystyle,
                             "action":
                                 {"@show_in":"MODAL_WINDOW",
                                  "#sorted":
                                    [{"main_context":'current'},
                                     {"modalwindow":
                                        {"@caption":"Создание копии БТЗ",
                                         "@height":"400",
                                         "@width":"600"
                                         }
                                      },
                                     {"datapanel":
                                        {"@type":"current",
                                         "@tab":"current",
                                         "element":
                                             {"@id":'createBtzCopyCard',
                                              "add_context": ""}
                                        }
                                     }]
                                 }
                             }
    
                           },        
                    ]}},                            
                     {"item":
                         {"@text":u"Режим работы с ТЗ",
                         "@hint":u"Режим работы с ТЗ",
                         "@disable":editstyle,
                         "action": {
                            "#sorted": [
                                {"main_context":'current'},
                                {"client": {
                                    "activity": [
                                        {"@id": "btzEditMode",
                                        "@name": "goToLink2",
                                        "add_context": u'?userdata=authoring&mode=btz&package=%s' % (package_id)}]}}]}}},                     
                      {"item":
                        {"@text":u"Задать глобальные настройки",
    #                    "@img":"bad.png",
                         "@hint":u"Задать глобальные настройки",
                         "@disable":change_status_style,
                         "action":
                             {"@show_in":"MODAL_WINDOW",
                              "#sorted":
                                [{"main_context":'current'},
                                 {"modalwindow":
                                    {"@caption":"Задать глобальные настройки",
                                     "@height":"750",
                                     "@width":"900"
                                     }
                                  },
                                 {"datapanel":
                                    {"@type":"current",
                                     "@tab":"current",
                                     "element":
                                         {"@id":'setGlobalSettingsCard',
                                          "add_context": ""}
                                    }
                                 }]
                             }
                         }

                       },
                     {"item":
                        {"@text":u"Создать БТЗ из нескольких БТЗ",
    #                    "@img":"bad.png",
                         "@hint":u"Создать БТЗ из нескольких БТЗ",
                         "@disable":add_style,
                         "action":
                             {"@show_in":"MODAL_WINDOW",
                              "#sorted":
                                [{"main_context":'current'},
                                 {"modalwindow":
                                    {"@caption":"Создание БТЗ из нескольких БТЗ",
                                     "@height":"450",
                                     "@width":"600"
                                     }
                                  },
                                 {"datapanel":
                                    {"@type":"current",
                                     "@tab":"current",
                                     "element":
                                         {"@id":'createBtzFromManyBtzCard',
                                          "add_context": ""}
                                    }
                                 }]
                             }
                         }
                      },
                    {"group":  {
                        "@text": u"Экспорт/импорт БТЗ",
                        "#sorted": [
                             {"item":
                                {"@text":u"Загрузить БТЗ",
            #                    "@img":"bad.png",
                                 "@hint":u"Загрузить БТЗ",
                                 "@disable":"false",
                                 "action":
                                     {"@show_in":"MODAL_WINDOW",
                                      "#sorted":
                                        [{"main_context":'current'},
                                         {"modalwindow":
                                            {"@caption":"Загрузка БТЗ",
                                             "@height":"200",
                                             "@width":"460"
                                             }
                                          },
                                         {"datapanel":
                                            {"@type":"current",
                                             "@tab":"current",
                                             "element":
                                                 {"@id":'uploadBtzCard',
                                                  "add_context": ""}
                                            }
                                         }]
                                     }
                                 }
                              },
                             {"item":
                                {"@text":u"Загрузить архив БТЗ",
            #                    "@img":"bad.png",
                                 "@hint":u"Загрузить архив БТЗ",
                                 "@disable":"false",
                                 "action":
                                     {"@show_in":"MODAL_WINDOW",
                                      "#sorted":
                                        [{"main_context":'current'},
                                         {"modalwindow":
                                            {"@caption":"Загрузка архива БТЗ",
                                             "@height":"200",
                                             "@width":"400"
                                             }
                                          },
                                         {"datapanel":
                                            {"@type":"current",
                                             "@tab":"current",
                                             "element":
                                                 {"@id":'uploadBtzArchiveCard',
                                                  "add_context": ""}
                                            }
                                         }]
                                     }
                                 }
                              },
                             {"item":
                                {"@text":u"Загрузить БТЗ из Excel",
            #                    "@img":"bad.png",
                                 "@hint":u"Загрузить БТЗ из Excel",
                                 "@disable":"false",
                                 "action":
                                     {"@show_in":"MODAL_WINDOW",
                                      "#sorted":
                                        [{"main_context":'current'},
                                         {"modalwindow":
                                            {"@caption":"Загрузка БТЗ из Excel",
                                             "@height":"200",
                                             "@width":"460"
                                             }
                                          },
                                         {"datapanel":
                                            {"@type":"current",
                                             "@tab":"current",
                                             "element":
                                                 {"@id":'uploadBtzExcelCard',
                                                  "add_context": ""}
                                            }
                                         }]
                                     }
                                 }
                              },
                             {"separator": {}},
                             {"item":
                                {"@text":u"Скачать БТЗ",
            #                    "@img":"bad.png",
                                 "@hint":u"Скачать БТЗ",
                                 "@disable":downLoadStyle,
                                 "action":
                                     {"@show_in":"MODAL_WINDOW",
                                      "#sorted":
                                        [{"main_context":'current'},
                                         {"modalwindow":
                                            {"@caption":u"Скачать БТЗ",
                                             "@height":"200",
                                             "@width":"400"
                                             }
                                          },
                                         {"datapanel":
                                            {"@type":"current",
                                             "@tab":"current",
                                             "element":
                                                 {"@id":'downloadBtzCard',
                                                  "add_context": ""}
                                            }
                                         }]
                                     }
                                 }
                              },
                             {"item":
                                {"@text":u"Экспорт БТЗ в Excel",
            #                    "@img":"bad.png",
                                 "@hint":u"Экспорт БТЗ в формате MS Exccel",
                                 "@disable": downLoadStyle,
                                 "action":
                                     {"@show_in":"MODAL_WINDOW",
                                      "#sorted":
                                        [{"main_context":'current'},
                                         {"modalwindow":
                                            {"@caption":u"Экспорт БТЗ в формате MS Exccel",
                                             "@height":"200",
                                             "@width":"400"
                                             }
                                          },
                                         {"datapanel":
                                            {"@type":"current",
                                             "@tab":"current",
                                             "element":
                                                 {"@id":'downloadBtzExcelCard',
                                                  "add_context": ""}
                                            }
                                         }]
                                     }
                                 }
                              }
                    ]}},
                    {"item":
                        {"@text":u"Публикация БТЗ",
    #                    "@img":"bad.png",
                         "@hint":u"Опубликовать БТЗ",
                         "@disable":editstyle,
                         "action":
                             {"@show_in":"MODAL_WINDOW",
                              "#sorted":
                                [{"main_context":'current'},
                                 {"modalwindow":
                                    {"@caption":"Публикация БТЗ",
                                     "@height":"300",
                                     "@width":"500"
                                     }
                                  },
                                 {"datapanel":
                                    {"@type":"current",
                                     "@tab":"current",
                                     "element":
                                         {"@id":'publishBtzCard',
                                          "add_context": ""}
                                    }
                                 }]
                             }
                         }
                      },
                    {"item":
                        {"@text":u"Проверка БТЗ",
    #                    "@img":"bad.png",
                         "@hint":u"Проверить БТЗ",
                         "@disable":editstyle,
                         "action":
                             {"@show_in":"MODAL_WINDOW",
                              "#sorted":
                                [
                                 {"main_context":'current'},
                                 {"modalwindow":
                                    {"@caption":"Проверка БТЗ",
                                     "@height":"130",
                                     "@width":"440"
                                     }
                                  },
                                 {"datapanel":
                                    {"@type":"current",
                                     "@tab":"current",
                                     "element":
                                         {"@id":'testBtzCard',
                                          "add_context": ""}
                                    }
                                 }
                                

                                 ]
                             }
                         }
                      },
                    {"item":
                        {"@text":u"Сформировать варианты",
    #                    "@img":"bad.png",
                         "@hint":u"Сформировать варианты",
                         "@disable":editstyle,
                         "action":
                             {"@show_in":"MODAL_WINDOW",
                              "#sorted":
                                [
                                 {"main_context":'current'},
                                 {"modalwindow":
                                    {"@caption":"Сформировать варианты",
                                     "@height":"300",
                                     "@width":"500"
                                     }
                                  },
                                 {"datapanel":
                                    {"@type":"current",
                                     "@tab":"current",
                                     "element":
                                         {"@id":'createVariantsCard',
                                          "add_context": ""}
                                    }
                                 }
                                

                                 ]
                             }
                         }
                     }
                    
                     ]
                     }
                 }




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


def selectBTZ(context, main=None, add=None, filterinfo=None, session=None):
    u'''Запоминаем выбрраный БТЗ, чтобы использовать его при редактировании. '''

    context.getData()['btzSelectedForEditQuestions'] = add

def externalFilter(context, cursor, extfilter):
    u'''Применяем внешний фильтр на курсор. '''

    if extfilter['statusId'] != '':
        cursor.setRange('Status', extfilter['statusId'])
#     if extfilter['cath_id'] != '':
#         cursor.setRange('cath_id', extfilter['cath_id'])
#     if extfilter['authorId'] != '':
#         cursor.setRange('author', extfilter['authorId'])
#     if extfilter['exauthorId'] != '':
#         cursor.setRange('extauthor', extfilter['exauthorId'])
    # Фильт по названию
    if extfilter["eor_name"]:
        name = "@%%'%s'%%" % extfilter["eor_name"] if extfilter["eor_name"] else "%"
        cursor.setFilter("PackageName", name)
    # Фильт по специальностям
#     if extfilter["spec"]:
#         data = extfilter["spec"]["item"]
#         if isinstance(data, dict):
#             data = [data]
#         filter = "|".join(map(lambda x: "@%%'%s'%%" % x["id"], data))
#         cursor.setFilter("spec_id", filter)
#     # Фильт по ДПП
#     if extfilter["dpp"]:
#         data = extfilter["dpp"]["item"]
#         if isinstance(data, dict):
#             data = [data]
#         filter = "|".join(map(lambda x: "@%%'%s'%%" % x["id"], data))
#         cursor.setFilter("for_what_dev", filter)
#     # Фильт по НМО
#     if extfilter["nmo"]:
#         data = extfilter["nmo"]["item"]
#         if isinstance(data, dict):
#             data = [data]
#         filter = "|".join(map(lambda x: "@%%'%s'%%" % x["id"], data))
#         cursor.setFilter("for_what_dev", filter)


    # cursor.setComplexFilter(q)

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