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

@author: v.popov
'''
import json
import xml.dom.minidom as minidom
from java.util import ArrayList
from qt._qt_orm import QtiQuestionCursor, QtiResourceCursor
import uuid
from fileRepository._fileRepository_orm import fileCursor
from qt.functions import getImageById
from java.io import OutputStreamWriter
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'''Данные для карточки.'''
    sessionContext = json.loads(session)['sessioncontext']

    themeId = main
    try:
        questionId = sessionContext["related"]["gridContext"]["currentRecordId"]
    except:
        questionId = ''

    btzAnswerGridAction = 'hide'
    btzAnswerGridKeepUserSettings = 'false'
    # Структура данных
    xformsdata = {"schema": {
                    "@xmlns":"",
                    "data": {
                        "question_id": questionId,
                        "theme_id": themeId,
                        "question_html": '',
                        "question_img_file": unicode(uuid.uuid4()),
                        "question_img_file_name": '',
                        "question_img_path": 'fc0001/pictures/',
                        "question_images": '',
                        "question_html2": '',
                        "question_type": '',
                        "question_order": ''}}}

    if add == 'edit':
        QtiQuestion = QtiQuestionCursor(context)
        QtiQuestion.get(questionId)
        questionType = int(QtiQuestion.QuestionType)
        xformsdata['schema']['data']['theme_id'] = QtiQuestion.ThemeID
        xformsdata['schema']['data']['question_html'] = QtiQuestion.QuestionHtml.replace('&nbsp;', ' ') if QtiQuestion.QuestionHtml else None
        xformsdata['schema']['data']['question_html2'] = QtiQuestion.QuestionHtml2.replace('&nbsp;', ' ') if QtiQuestion.QuestionHtml2 else None
        xformsdata['schema']['data']['question_type'] = QtiQuestion.QuestionType
        xformsdata['schema']['data']['question_order'] = QtiQuestion.QuestionOrder
        imgId = QtiQuestion.QuestionImg
        if imgId:
            xformsdata['schema']['data']['question_img_file'] = imgId
            if questionType == 7:
                file_cursor = fileCursor(context)
                file_cursor.get(imgId)
                xformsdata['schema']['data']['question_img_file_name'] = file_cursor.name
                file_cursor.close()
            else:
                QtiResource = QtiResourceCursor(context)
                imgData = getImageById(QtiResource, imgId, isImage=False)
                if imgData:
                    xformsdata['schema']['data']['question_images'] = json.loads(imgData)
                QtiResource.close()
            
        QtiQuestion.close()
        btzAnswerGridAction = ''
        btzAnswerGridKeepUserSettings = 'true'

    # Первоначальная xformssettings
    xformssettings = {"properties": {
                        "event": [
                            {"@name":"single_click",
                             "@linkId": "1",
                             "action": {
                                "#sorted": [
                                    {"main_context": "current"},
                                    {"datapanel": {
                                        "@type": "current",
                                        "@tab": "current",
                                        "element": {
                                            "@id":'webQuestionGrid',
                                            "@keep_user_settings": btzAnswerGridKeepUserSettings,
                                            "add_context": btzAnswerGridAction}}}]}},
                            {"@name":"single_click",
                             "@linkId": "2",
                             "action": {
                                "#sorted": [
                                    {"main_context": "current"},
                                    {"datapanel": {
                                        "@type": "current",
                                        "@tab": "current",
                                        "element": {
                                            "@id":'webQuestionGrid',
                                            "@keep_user_settings": "true",
                                            "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)['schema']['data']
    QtiQuestion = QtiQuestionCursor(context)
    
    questionType = int(data_dict['question_type'])
    hasImages = True if data_dict['question_images'] else False 
    if hasImages:
        imgId = unicode(uuid.uuid4())
    else:
        imgId = None 
        
    if add == 'add':        
        QtiQuestion.QuestionID = unicode(uuid.uuid4())
        QtiQuestion.ThemeID = data_dict['theme_id']
        QtiQuestion.QuestionHtml = data_dict['question_html']
        QtiQuestion.QuestionHtml2 = data_dict['question_html2']
        QtiQuestion.QuestionType = questionType
        QtiQuestion.QuestionOrder = data_dict['question_order']
        QtiQuestion.QuestionImg = data_dict['question_img_file'] if questionType == 7 else imgId
        if QtiQuestion.tryInsert() and hasImages:
            QtiResource = QtiResourceCursor(context)
            QtiResource.ResourceID = imgId
            QtiResource.ResourceName = 'Image files'
            QtiResource.calcResourceData()
            inageResource = OutputStreamWriter(QtiResource.ResourceData.getOutStream(), 'utf-8')
            try:
                inageResource.append(data_dict['question_images'])
            finally:
                inageResource.close()
            QtiResource.insert()
            QtiResource.close()
                        
    elif add == 'edit':
        # id записи
        if hasImages:
            imgId = data_dict['question_img_file']
        QtiQuestion.get(data_dict['question_id'])
        QtiQuestion.ThemeID = data_dict['theme_id']
        QtiQuestion.QuestionHtml = data_dict['question_html']
        QtiQuestion.QuestionHtml2 = data_dict['question_html2']
        QtiQuestion.QuestionType = questionType
        QtiQuestion.QuestionOrder = data_dict['question_order']
        QtiQuestion.QuestionImg = data_dict['question_img_file'] if questionType == 7 else imgId
        if QtiQuestion.tryUpdate() and hasImages:
            QtiResource = QtiResourceCursor(context)
            
            if hasImages:
                getResource = QtiResource.tryGet(imgId)
                                    
                QtiResource.calcResourceData()
                inageResource = OutputStreamWriter(QtiResource.ResourceData.getOutStream(), 'utf-8')
                
                try:
                    inageResource.append(json.dumps(data_dict['question_images']))
                finally:
                    inageResource.close()
                    
                if getResource:
                    QtiResource.update()
                else:
                    QtiResource.ResourceID = imgId
                    QtiResource.ResourceName = 'Image files'
                    QtiResource.insert()
            else:
                if QtiResource.tryGet(data_dict['question_img_file']):
                    QtiResource.delete()               
                
            QtiResource.close()
        
    QtiQuestion.close()


def imageSelector(context, main=None, add=None, filterinfo=None, session=None, params=None, curValue=None, startsWith=None, firstRecord=None, recordCount=None):
    u'''Селектор выбора файла '''
    file_cursor = fileCursor(context)
#     params = json.loads(XMLJSONConverter.xmlToJson(params))
    file_cursor.setFilter('name', "@%s'%s'%%" % ('%' * (not startsWith), curValue))
    file_cursor.limit(firstRecord, recordCount)
    recordList = ArrayList()
    for row in file_cursor.iterate():
        rec = DataRecord()
        rec.setId(row.id)
        rec.setName(row.name)
        recordList.add(rec)
    return ResultSelectorData(recordList, len(recordList))


def htmlEdit(context, main, add, filterinfo, session, elementId):
    jsonData = json.loads(filterinfo)
    try:
        html = jsonData['schema']['filter']['question_html']
    except:
        try:
            html = jsonData['schema']['filter']['html']
        except:
            html = jsonData['schema']['filter']['destructor']
#     data = u'''<div>%s</div>''' % htmlText
    data = html.replace('&lt;', '<').replace('&gt;', '>').replace('&lt', '<').replace('&gt', '>').replace('&nbsp;', ' ').replace('&nbsp', ' ')
    try:
        minidom.parseString(data)
    except:
        data = "<div>%s</div>" % data
    settings = u'''
    <properties>
    </properties>
    '''
    # raise Exception(main, add, filterinfo, session, elementId)
    res = JythonDTO(data, settings)
    return res

    
def html2Edit(context, main, add, filterinfo, session, elementId):
    jsonData = json.loads(filterinfo)
    try:
        html = jsonData['schema']['filter']['question_html2']
    except:
        try:
            html = jsonData['schema']['filter']['html']
        except:
            html = jsonData['schema']['filter']['destructor']

    data = html.replace('&lt;', '<').replace('&gt;', '>').replace('&lt', '<').replace('&gt', '>').replace('&nbsp;', ' ').replace('&nbsp', ' ')
    try:
        minidom.parseString(data)
    except:
        data = "<div>%s</div>" % data
    settings = u'''<properties></properties>'''
    res = JythonDTO(data, settings)
    return res
    