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

@author: Victor B.
'''
import uuid
import simplejson as json
import time
from java.text import SimpleDateFormat

from ru.curs.celesta.showcase.utils import XMLJSONConverter
from common.sysfunctions import toHexForXml
from qt._qt_orm import QtiPackageAttributeCursor

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):
    begin = time.time()
    session = json.loads(session)
    extfilter = {'cath_id': '',
                 'cath_name': '',
                 "spec_id": "",
                 "spec_name": "",
                 "program_id": "",
                  "program_name": "",
                  "cycle_id": "",
                  "cycle_dates": "",
                  "status": "-",
                  "exam_date_from": "",
                  "exam_date_to": "",
                  "examinee_fio": ""
                 }
    if 'xformsContext' in session['sessioncontext']['related']:
        if 'formData' in session['sessioncontext']['related']['xformsContext']:
            extfilter = session['sessioncontext']['related']['xformsContext']['formData']['schema']['data']
    # PersonFUV = PersonFUVCursor(context)
    qti_pa = QtiPackageAttributeCursor(context)
    print 'filter',time.time() - begin
    # применяем внешний фильтр
    # externalFilter(context, ces, extfilter)
    try:
        package_id = session['sessioncontext']['related']['gridContext']['currentRecordId']
    except:
        package_id = None
    qti_pa.setRange('PackageID', package_id)
    qti_pa.orderBy('AttributeName')
    qti_pa.limit(firstrecord - 1, pagesize)

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

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

    print 'range',time.time() - begin
    for rec in qti_pa.iterate():
        currentrow = {}
        currentrow[toHexForXml("~~id")] = rec.AttributeID
        currentrow[toHexForXml(u"Название атрибута")] = rec.AttributeName
        currentrow[toHexForXml(u"Значение атрибута")] = rec.AttributeValue

        currentrow["properties"] = {"event":
                                                    {"@name":"row_single_click",
#                         "action":
#                             {
#                              "#sorted":
#                                [{"main_context":'current',
#                                 "datapanel":{"@type":"current","@tab":"current"}},
#                                 {"server": {"activity": {"@id": "selectPerson",
#                     "@name": "journals.grid.personsgrid.selectPerson.celesta",
#                     "add_context": ""
#                                                         }
#
#                                            }
#                                  }
#                                 ]
#                             }
                                              "action":{
                                                  "#sorted": [
                                                      {"main_context":"current"},
                                                         {"datapanel":
                                                             {"@type":"current",
                                                              "@tab":"current"
                                                         }
                                                     }]}
                                                }
                                            }
        data['records']['rec'].append(currentrow)

#    raise Exception(data)
    print 'cycle',time.time() - begin
    return JythonDTO(XMLJSONConverter.jsonToXml(json.dumps(data)), None)

def gridMeta(context, main=None, add=None, filterinfo=None, session=None, elementId=None, sortColumnList=None):
    begin = time.time()
    session = json.loads(session)
    extfilter = {'cath_id': '',
                 'cath_name': '',
                 "spec_id": "",
                 "spec_name": "",
                 "program_id": "",
                  "program_name": "",
                  "cycle_id": "",
                  "cycle_dates": "",
                  "status": "-",
                  "exam_date_from": "",
                  "exam_date_to": "",
                  "examinee_fio": ""
                 }
    if 'xformsContext' in session['sessioncontext']['related']:
        if 'formData' in session['sessioncontext']['related']['xformsContext']:
            extfilter = session['sessioncontext']['related']['xformsContext']['formData']['schema']['data']
    # raise Exception(extfilter)
    # PersonFUV = PersonFUVCursor(context)
    print 'filter_meta',time.time() - begin
    qti_pa = QtiPackageAttributeCursor(context)

    # применяем внешний фильтр
    # externalFilter(context, ces, extfilter)
    try:
        package_id =  session['sessioncontext']['related']['gridContext']['currentRecordId']
    except:
        package_id = None
    qti_pa.setRange('PackageID', package_id)
    # userDepartmentFilter(context, session, ces)
    # применяем внешний фильтр
    # externalFilter(context, ces, extfilter)
#    PersonFUV.setFilter('surname', "!null")
    print 'range_meta',time.time() - begin
    dpwidth = session['sessioncontext']['currentDatapanelWidth']
    dpheight =  session['sessioncontext']['currentDatapanelHeight']
    totalCount = qti_pa.count()
    meta = {"gridsettings":
                    {"labels":
                        {"header":
                            {"b":u"Доп. атрибуты БТЗ"}
                        },
#                     "action":
#                        {"#sorted":
#                            [{"main_context":'current'},
#                             {"datapanel":
#                                {"@type":'current',
#                                 "@tab":'current'
# #                                 ,
# #                                 "element":
# #                                    {"@id":22}
#                                 }
#                              }]
#                         },
                     "columns":
                        {"col":
                            [{"@id":u'Название атрибута'},
                             {"@id":u'Значение атрибута'}
                        ]
                         },
                     "properties":
                        {"@flip":"false",
                        "@pagesize":50,
                        "@totalCount":totalCount,
#                         "@gridWidth": "%dpx" % (int(dpwidth) - 51) if dpwidth not in ('0', '', 0) else "800px",
                        "@gridWidth": "100%",
                        "@gridHeight":int(int(dpheight) * 0.3),
                        "@profile":"default.properties"
                        }
                    }
                }

#    raise Exception(meta)
    print 'meta_meta',time.time() - begin
    return JythonDTO(None, XMLJSONConverter.jsonToXml(json.dumps(meta)))

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

    session = json.loads(session)
    addStyle = "false"
    changestatus_style = "true"
    
    gridContext = session["sessioncontext"]["related"]["gridContext"]
    
    for grid in gridContext:
        if grid["@id"] == "btzAttributesGrid":
            attributeId = grid.get("currentRecordId")
    
    if attributeId:
        editStyle = "false"
        deleteStyle = "false"
        changestatus_style = "false"        
    else:
        editStyle = "true"
        deleteStyle = "true"


#    raise Exception(currentRecordId)
    data = {"gridtoolbar":
                {"#sorted":
                    [
                     {"item":
                        {"@text":u"Добавить",
    #                    "@img":"bad.png",
                         "@hint":u"Добавить",
                         "@disable":addStyle,
                         "action":
                             {"@show_in":"MODAL_WINDOW",
                              "#sorted":
                                [{"main_context":'current'},
                                 {"modalwindow":
                                    {"@caption":"Добавление атрибута",
                                     "@height":"450",
                                     "@width":"600"
                                     }
                                  },
                                 {"datapanel":
                                    {"@type":"current",
                                     "@tab":"current",
                                     "element":
                                         {"@id":'btzAttributesAddEditCard',
                                          "add_context": "add"}
                                    }
                                 }]
                             }
                         }
                      },
                      {"item":
                         {"@text":u"Редактировать",
                         "@hint":u"Редактировать",
                         "@disable":editStyle,
                         "action":
                             {"@show_in":"MODAL_WINDOW",
                              "#sorted":
                                [{"main_context":'current'},
                                 {"modalwindow":
                                    {"@caption":"Редактирование атрибута",
                                     "@height":"450",
                                     "@width":"600"
                                     }
                                  },
                                 {"datapanel":
                                    {"@type":"current",
                                     "@tab":"current",
                                     "element":
                                         {"@id":'btzAttributesAddEditCard',
                                          "add_context": "edit"}
                                    }
                                 }]
                             }
                          }
                       },
                     {"item":
                         {"@img": 'gridToolBar/deleteDocument.png',
                             "@text":"Удалить",
                             "@hint":"Удалить",
                             "@disable": deleteStyle,
                             "action":{"@show_in": "MODAL_WINDOW",
                                       "#sorted":[{"main_context":"current"},
                                                  {"modalwindow":{"@caption": "Удаление записи",
                                                                  "@height": "200",
                                                                  "@width": "450"
                                                                  }
                                                   },
                                                  {"datapanel":{"@type": "current",
                                                                "@tab": "current",
                                                                "element": {"@id": "btzAttributesDeleteCard",
                                                                            "add_context":"delete"}
                                                                }
                                                   }]
                                       }
                                     }
                       }]
                     }
                 }


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

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

    if extfilter['status'] != '-':
        cursor.setRange('status_id', extfilter['status'])
    if extfilter['exam_date_from'] != '' and extfilter['exam_date_to'] != '':
        cursor.setRange('exam_date', extfilter['exam_date_from'], extfilter['exam_date_to'])
    elif extfilter['exam_date_from'] != '' and extfilter['exam_date_to'] == '':
        cursor.setRange('exam_date', extfilter['exam_date_from'], '2100-01-01')
    elif extfilter['exam_date_from'] == '' and extfilter['exam_date_to'] != '':
        cursor.setRange('exam_date', '1900-01-01', extfilter['exam_date_to'])
    if extfilter['cath_id'] != '':
        cursor.setRange('cath_id', extfilter['cath_id'])
    if extfilter['spec_id'] != '':
        cursor.setRange('spec_id', extfilter['spec_id'])
    if extfilter['cycle_id'] != '':
        cursor.setRange('associated_cycle_id', extfilter['cycle_id'])


    # cursor.setComplexFilter(q)

