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

@author: v.popov
'''

import simplejson as json
from java.io import FileOutputStream, FileInputStream
from qt._qt_orm import QtiPackageCursor, QtiThemeCursor, \
    QtiPackageAttributeCursor, QtiQuestionCursor, QtiDestructorCursor, ContentCursor, Content_AttributeValueCursor

from org.apache.poi.xssf.usermodel import XSSFWorkbook
from org.apache.poi.ss.usermodel import HorizontalAlignment, BorderStyle, VerticalAlignment
import os

import tempfile

# from catalogs._catalogs_orm import cycles_viewCursor, faculty_departmentCursor

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

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

from qt.functions import MATCHING_ATTRIBUTE_PACKAGE, MATCHING_NUMBERS_SHORT, MATCHING_NUMBERS, cleanString

def cardData(context, main=None, add=None, filterinfo=None, session=None, elementId=None):
    u'''Данные для карточки.'''
    
    package = QtiPackageCursor(context)
    session = json.loads(session)
    gridContext = session['sessioncontext']['related']['gridContext']
    
    if "currentRecordId" in gridContext:
        currentRecordId = gridContext["currentRecordId"]
        package.get(currentRecordId)

    btzName = package.PackageName
    # Структура данных
    xformsdata = {"schema":
                  {"context":
                   {"@id": "downloadBtz",
                    "@btzName": btzName,
                    }}}

    xformssettings = {"properties":{"event":{"@name":"single_click",
                                             "@linkId": "1",
                                             "action":{
                                                  "#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 downloadBtzCard(context, main=None, add=None, filterInfo=None, session=None, elementId=None, xformsdata=None):
    u"""Функция выгрузки файлов БТЗ с сервера"""

    session = json.loads(session)
    gridContext = session['sessioncontext']['related']['gridContext']
    
    u"""Вытягивание выделенной записи и получение ID пакета"""
    try:
        packageId = gridContext['currentRecordId']
    except Exception as e:
        context.error(u"Произошла ошибка при получении ИД БТЗ: {}".format(e.message))
    
    btzName = u'БТЗ'
    
    template = "excel_template.xlsx"
    
    templateFile = FileInputStream(os.path.dirname(os.path.abspath(__file__)) + "/" + template)
    wb = XSSFWorkbook(templateFile)
    
    sheetBtz = wb.getSheet(u'БТЗ')
    if sheetBtz is None:
        context.error(u'Лист "БТЗ" в шаблоне не найден')
        
    sheetQuestions = wb.getSheet(u'Вопросы')
    if sheetQuestions is None:
        context.error(u'Лист "Вопросы" в шаблоне не найден')
    
    packageCur = QtiPackageCursor(context)
    if packageCur.tryGet(packageId):
        btzName = packageCur.PackageName
        row = sheetBtz.getRow(0)
        cell = row.getCell(1)
        if cell is None:
            cell = row.createCell(1)
        cell.setCellValue(btzName)
    else:
        context.error(u'БТЗ с ИД={} не найден'.format(packageId))
    
    packageCur.close()
    
    packageAttrCur = QtiPackageAttributeCursor(context)
    packageAttrCur.setRange('PackageID', packageId)
    
    rn = 1
    for r in range(1, 20, 1):
        row = sheetBtz.getRow(rn)
        packageAttrCur.setRange('AttributeName', MATCHING_ATTRIBUTE_PACKAGE.get(MATCHING_NUMBERS.get(r, ''), u''))
        if packageAttrCur.tryFirst():
            cell = row.getCell(1)
            cell.setCellValue(packageAttrCur.AttributeValue)
            rn = rn + 1
    
    packageAttrCur.close()
    
    styleCenter = wb.createCellStyle()
    styleCenter.setAlignment(HorizontalAlignment.CENTER)
    styleCenter.setBorderLeft(BorderStyle.THIN)
    styleCenter.setBorderRight(BorderStyle.THIN)
    styleCenter.setBorderTop(BorderStyle.THIN)
    styleCenter.setBorderBottom(BorderStyle.THIN)
    
    style = wb.createCellStyle()
    style.setAlignment(HorizontalAlignment.LEFT)
    style.setVerticalAlignment(VerticalAlignment.TOP)
    style.setBorderLeft(BorderStyle.THIN)
    style.setBorderRight(BorderStyle.THIN)
    style.setBorderTop(BorderStyle.THIN)
    style.setBorderBottom(BorderStyle.THIN)
    style.setWrapText(True)
    
    themeCur = QtiThemeCursor(context)
    themeCur.setRange('PackageID', packageId)
    themeCur.orderBy('ThemeOrder')
    
    questionCur = QtiQuestionCursor(context)
    questionCur.orderBy('ThemeID', 'QuestionOrder')
    
    destructorCur = QtiDestructorCursor(context)
    destructorCur.orderBy('QuestionID', 'DestructorOrder')
    
    rt = 21
    rq = 1
    for theme in themeCur.iterate():
        row = sheetBtz.getRow(rt)
        if row is None:
            row = sheetBtz.createRow(rt)
            
        themeOrder = theme.ThemeOrder
        cell = row.createCell(0)
        cell.setCellStyle(styleCenter)
        cell.setCellValue(themeOrder)
        
        cell = row.createCell(1)
        cell.setCellStyle(style)
        cell.setCellValue(theme.ThemeName)  
        
        themeId = theme.ThemeID
        
        questionCur.setRange('ThemeID', themeId)
        for question in questionCur.iterate():
            rowQ = sheetQuestions.getRow(rq)
            if rowQ is None:
                rowQ = sheetQuestions.createRow(rq)
                
            cell = rowQ.createCell(0)
            cell.setCellStyle(styleCenter)
            cell.setCellValue(themeOrder)
            
            questionType = question.QuestionType
            cell = rowQ.createCell(1)
            cell.setCellStyle(styleCenter)
            cell.setCellValue(questionType)
            
            cell = rowQ.createCell(2)
            cell.setCellStyle(style)
            cell.setCellValue(question.QuestionHtml)
            
            cd = 3
            
            questionId = questionCur.QuestionID
            
            destructorCur.setRange('QuestionID', questionId)
            for destructor in destructorCur.iterate():
                answer = cleanString(destructor.DestructorHtml)
                
                if destructor.IsTrue:
                    answer = '*' + answer
                    
                cell = rowQ.createCell(cd)
                cell.setCellStyle(style)    
                cell.setCellValue(answer)
                
                cd = cd + 1
                
            if cd < 13:
                for i in range(cd, 13, 1):
                    cell = rowQ.createCell(i)
                    cell.setCellStyle(style)                
                
            rq = rq + 1
        
        rt = rt + 1      
    
    destructorCur.close()
    questionCur.close()    
    themeCur.close()
    
    u"""Создание входного потока данных"""
    fileName = '%s.xlsx' % (packageId)
    
    fileOut = FileOutputStream(tempfile.gettempdir() + "/" + fileName)
    wb.write(fileOut)
    wb.close()
    templateFile.close()   
    fileOut.close()
     
    report = FileInputStream(tempfile.gettempdir() + "/" + fileName)  # загрузка архива из каталог данного скрипта
    
    u"""Возврат переконвертированного файла""" 
    return JythonDownloadResult(report, '%s.xlsx' % (btzName))
    # return JythonDownloadResult(FileInputStream('C:\\Lopatin_Ilya\\nav_setting_workable.txt'), u'%s' % (data_dict['schema']['context']['@btzName']))


def cardDataSave(context, main=None, add=None, filterinfo=None, session=None, elementId=None, xformsdata=None):
    session = json.loads(session)['sessioncontext']
