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

@author: v.popov
'''

from java.util import ArrayList
from author._author_orm import serviceCatalogCursor
from ru.curs.celesta.showcase.utils import XMLJSONConverter
import json

try:
    from ru.curs.showcase.core.jython import JythonDTO
    from ru.curs.showcase.core.jython import JythonDownloadResult
    from ru.curs.showcase.core.selector import ResultSelectorData
    from ru.beta2.extra.gwt.ui.selector.api import DataRecord
except:
    from ru.curs.celesta.showcase import JythonDTO

def webServicesListAndCount(context, main=None, add=None, filterinfo=None, session=None, params=None, curValue=None, startsWith=None, firstRecord=None, recordCount=None):

    data = procList(context, main, add, filterinfo, session, params, curValue, startsWith, firstRecord, recordCount)
    count = procCount(context, main, add, filterinfo, session, params, curValue, startsWith)
    return ResultSelectorData(data.getDataRecordList(), count.getCount())

def procCount(context, main=None, add=None, filterinfo=None, session=None, params=None,
                curvalue=None, startswith=None):
    u'''Функция count селектора PackageID '''

    serviceCatalog = serviceCatalogCursor(context)
#     params = json.loads(XMLJSONConverter.xmlToJson(params))

    serviceCatalog.setFilter('testSystemAddress', "@%s'%s'%%" % ('%' * (not startswith), curvalue))
    count = serviceCatalog.count()

    return ResultSelectorData(None, count)

def procList(context, main, add, filterinfo, session, params,
                curvalue, startswith, firstrecord, recordcount):
    u'''Функция list селектора PackageID '''

    serviceCatalog = serviceCatalogCursor(context)
#     params = json.loads(XMLJSONConverter.xmlToJson(params))

    serviceCatalog.setFilter('testSystemAddress', "@%s'%s'%%" % ('%' * (not startswith), curvalue))
    serviceCatalog.limit(firstrecord, recordcount)
    serviceCatalog.orderBy('testSystemAddress asc')
    recordList = ArrayList()
    for row in serviceCatalog.iterate():
        rec = DataRecord()
        rec.setId(unicode(row.catalogId))
        rec.setName(row.testSystemAddress)
        rec.addParameter('address',row.link)
        recordList.add(rec)

    return ResultSelectorData(recordList, 0)
