## Script (Python) "search_pins"
##bind container=container
##bind context=context
##bind namespace=
##bind script=script
##bind subpath=traverse_subpath
##parameters=REQUEST
##title=
##
# $Id: search_students.py 911 2006-11-20 15:11:29Z henrik $
"""
list Students for ClearanceOfficers
"""
try:
    from Products.zdb import set_trace
except:
    def set_trace():
        pass

import datetime

request = REQUEST
wftool = context.portal_workflow
mtool = context.portal_membership
member = mtool.getAuthenticatedMember()
roles = member.getRolesInContext(context)
pincat = context.portal_pins
students = context.portal_url.getPortalObject().campus.students
def check_hostel_pins(term):
    items = pincat(prefix_batch = term)
    not_found = []
    #from Products.zdb import set_trace;set_trace()
    for item in items:
        if item.student == '':
            continue
        student = getattr(students,item.student,None)
        if student is None:
            not_found.append(item)
        elif not "accommodation_2006" in student.objectIds():
            not_found.append(item)
        else:
            acco = student.accommodation_2006
            acco_doc = acco.getContent()
            pin = "".join(str(acco_doc.acco_res_sc_pin).split('-'))
            if pin != item.pin:
                not_found.append(item)
    return not_found

def set_used_pins(items, from_cat=False):
    l = []
    for i in items:
        item = {}
        if from_cat:
            sno = i.student
            prefix = i.prefix_batch
            serial = i.serial
            pin = i.pin
        else:
            sno = i['student']
            prefix = i.get('prefix_batch')
            serial = i.get('serial')
            pin = i.get('pin')
        item['student'] = sno
        item['prefix'] = prefix
        item['serial'] = serial
        if len(sno) > 0:
            item['pin'] = pin
        else:
            if str(member) in ('admin','isouaba'):
                item['pin'] = "%s" % (pin,)
            else:
                item['pin'] = "%s%s****%s" % (i.prefix_batch,pin[-10:-7],pin[-3:])

        if sno.startswith('disabled'):
            item['student_url'] = None
            item['student_id'] = sno
        elif len(sno)==10 or '/' in sno:
            #res = context.portal_catalog(SearchableText=sno,portal_type='StudentApplication')
            res = context.students_catalog(jamb_reg_no=sno.upper())
            if len(res) > 0:
                item['student_url'] = "%s/campus/students/%s/application" % (context.portal_url(),res[0].id)
                item['student_id'] = res[0].id
            else:
                item['student_url'] = None
                item['student_id'] = ''
        elif len(sno) == 7:
            item['student_url'] = '%s/campus/students/%s' % (context.portal_url(),item['student'])
            item['student_id'] = item['student']
        elif sno.startswith(prefix):
            item['student_url'] = None
            item['student_id'] = ''        
        else:
            item['student_url'] = ''
            item['student_id'] = "not used"
        l.append(item)
    return l

lt = context.portal_layouts
validate = request.has_key("cpsdocument_edit_button")
default = {'search_mode': 'student',}
rend,psm,ds = lt.renderLayout(layout_id= 'scratch_card_search',
                      schema_id= 'student_search',
                      context=context,
                      mapping=validate and request,
                      ob=default,
                      layout_mode='edit',
                      formaction="search_pins",
                      commit = False,
                      )
info = {}
info['used'] = []
#from Products.zdb import set_trace;set_trace()
if context.portal_type == "ScratchCardBatch":
    info['batch_doc'] = context.getContent()
    #info['used'] = set_used_pins(info['batch_doc'].getUsedPins())
    info['used'] = []
    info['unused'] = info['batch_doc'].getUnusedPins()
    info['nr_used'] = info['batch_doc'].getNumberOfUsedPins()
    view = context.batch_view
elif context.portal_type == "ScratchCardBatchesFolder":

    batches = []
    for id, object in context.objectItems():
        batch = {}
        batch['id'] = id
        batch['date'] = object.creation_date
        batch['url'] = object.absolute_url()
        batch['date_str'] = object.creation_date.strftime("%d/%m/%y")
        batches.append(batch)
    batches.sort(cmp=lambda x,y: cmp(x['id'].lower(), y['id'].lower()))
    #batches.sort(cmp=lambda x,y: cmp(x['date'], y['date']))

    #from Products.zdb import set_trace;set_trace()
    #batches = context.objectIds()
    #batches.sort()
    l = []
    cols = 4
    rows,rest = divmod(len(batches),cols)
    bis = 0
    for r in range(rows):
        von = r*cols
        bis = von + cols
        l += batches[von:bis],
    if rest:
        von = bis
        l += batches[von:von+rest],
    info['batches'] = l
    view = context.pins_view
if psm == '':
    return view(rendered = rend,
                psm = psm,
                #psm = "%s, %s" % (psm,ds),
                info = info,
                allowed = True,
                )
what = ds.get('search_mode')
term = ds.get('search_string')

items=[]
if term != "":
    if what == 'student' :
        items_1 = pincat(student = term.upper())
        items_2 = pincat(student = term.lower())
        items = items_1 + items_2
    elif what == 'pin':
        term = term.replace('-','').strip().upper()
        if context.portal_type == "ScratchCardBatch" and term == "HOS1":
            items = check_hostel_pins(term)
        else:
            items = pincat(pin = term)
    elif what == 'serial':
        try:
            snr = int(term.strip())
            items = pincat(serial = snr)
        except ValueError:
            psm = "invalid number"
            items = []
            pass
    else:
        items = []

info['used'] = set_used_pins(items,from_cat=True)



return view(rendered = rend,
            psm = psm,
            #psm = "%s, %s" % (psm,ds),
            info = info,
            allowed = True,
            )

