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

@author: Victor B.
'''

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


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
# from journals.functions import personIdFromSID


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

    # Структура данных
    xformsdata = {"schema":
                  {"@xmlns":"",
                    "data":
                        {
                        "package_name": '',
                        "selected_btz_status": 'ready'
                         }

                    }
                  }

    # Первоначальная 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":'btzCatalogGrid',
                                                                                 "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'''Сохранение карточки. '''

    data_dict = json.loads(xformsdata)
    # raise Exception(data_dict)
    # id btz
    selected_btz_json = data_dict['schema']['data']['selected_btz']
    selected_btz_ids = []
    if isinstance(selected_btz_json, list):
        for x in selected_btz_json:
            selected_btz_ids.append(x['@id'])
    else:
        selected_btz_ids.append(selected_btz_json['@id'])
    # qti_original = json.loads(session)['sessioncontext']['related']['gridContext']['currentRecordId']
    #
    person_id = json.loads(session)['sessioncontext']['sid']
    # копируем БТЗ
    copyManyBtzToOne(context, selected_btz_ids, person_id, data_dict['schema']['data']['package_name'])

#    arg_dict = {'script': 'elc.xforms.createBtzCopyCard.copyTaskFlute',
#                'request_id': unicode(uuid.uuid4()),
#                'params': {'qti_originals': selected_btz_ids,
#                'person_id': person_id,
#                'package_name': data_dict['schema']['data']['package_name']}}
#
#    addTask(context, arg_dict)

def copyManyBtzToOne(context, original_ids, editor_id, package_name):
    u'''Копирует несколько БТЗ в один. '''

    QtiPackage = QtiPackageCursor(context)
    QtiPackage1 = QtiPackageCursor(context)
    QtiPackageAttribute = QtiPackageAttributeCursor(context)
    QtiPackageAttribute1 = QtiPackageAttributeCursor(context)
    QtiTheme = QtiThemeCursor(context)
    QtiTheme1 = QtiThemeCursor(context)
    QtiQuestion = QtiQuestionCursor(context)
    QtiQuestion1 = QtiQuestionCursor(context)
    QtiDestructor = QtiDestructorCursor(context)
    QtiDestructor1 = QtiDestructorCursor(context)
    #
    new_id = uuid.uuid4()
    QtiPackage.get(original_ids[0])
    QtiPackage.PackageID = new_id
    QtiPackage.PackageName = package_name
    QtiPackage.DateCreated = datetime.datetime.now()
    QtiPackage.Status = u'forming'
    QtiPackage.EditorID = editor_id
    QtiPackage.insert()

    # берем атрибуты от первого ЬТЗ
    QtiPackageAttribute.setRange('PackageID', original_ids[0])
    for QtiPackageAttribute in QtiPackageAttribute.iterate():
        QtiPackageAttribute1.clear()
        QtiPackageAttribute1.copyFieldsFrom(QtiPackageAttribute)
        QtiPackageAttribute1.AttributeID = uuid.uuid4()
        QtiPackageAttribute1.PackageID = new_id
        QtiPackageAttribute1.insert()

    # берем темы от всех БТЗ
    theme_number = 1
    for original_id in original_ids:
        #
        QtiPackage1.get(original_id)
        QtiTheme.clear()
        QtiTheme.setRange('PackageID', original_id)
        for QtiTheme in QtiTheme.iterate():
            QtiQuestion.setRange('ThemeID', QtiTheme.ThemeID)
            QtiTheme1.clear()
            QtiTheme1.copyFieldsFrom(QtiTheme)
            # новое название темы из старой + название оригинального БТЗ
            original_theme = QtiTheme1.ThemeName
            QtiTheme1.ThemeName = u'%s (%s)' % (original_theme, QtiPackage1.PackageName)
            QtiTheme1.ThemeID = uuid.uuid4()
            QtiTheme1.ThemeOrder = theme_number
            QtiTheme1.PackageID = new_id
            QtiTheme1.insert()
            theme_number += 1
            for QtiQuestion in QtiQuestion.iterate():
                QtiDestructor.setRange('QuestionID', QtiQuestion.QuestionID)
                QtiQuestion1.clear()
                QtiQuestion1.copyFieldsFrom(QtiQuestion)
                QtiQuestion1.QuestionID = uuid.uuid4()
                QtiQuestion1.ThemeID = QtiTheme1.ThemeID
                QtiQuestion1.insert()
                for QtiDestructor in QtiDestructor.iterate():
                    QtiDestructor1.clear()
                    QtiDestructor1.copyFieldsFrom(QtiDestructor)
                    QtiDestructor1.DestructorID = uuid.uuid4()
                    QtiDestructor1.QuestionID = QtiQuestion1.QuestionID
                    QtiDestructor1.insert()



def copyTaskFlute(context, params):
    u'''Функция для копирования БТЗ через флейту.'''

    arg_dict = json.loads(params.params)

    # id записи
    qti_originals = arg_dict['qti_originals']
    #
    person_id = arg_dict['person_id']
    # копируем БТЗ
    copyManyBtzToOne(context, qti_originals, person_id, arg_dict['package_name'])


