##parameters=type_name, datamodel
# $Id: scratch_card_batch_create_do.py 5179 2010-04-30 06:39:44Z henrik $
"""
Create an empty object in the context according to the datamodel.

Datamodel may be examined to create a suitable id.
"""
from Products.CMFCore.utils import getToolByName

#try:
#    from Products.zdb import set_trace
#except:
#    def set_trace():
#        pass


prefix = datamodel.get('prefix').upper()
datamodel.set('prefix',prefix)
bl = context.portal_catalog({'meta_type': "ScratchCardBatch",})
b_ids = []

for b in bl:
    b_ids.append(b.getId)

p_ids = [p_id for p_id in b_ids if p_id.startswith(prefix)]
if p_ids:
    max_bno = max([int(bno.split('_')[1]) for bno in p_ids])
    next = max_bno+1
else:
    next = 1 

#next = 1
#while b_ids and "%s_%d" % (prefix,next) in b_ids:
#    next += 1

id = "%s_%d" % (prefix,next)

datamodel.set('batch_no',next)
new_id = context.invokeFactory(type_name, id, datamodel=datamodel,
                               )
if new_id is not None:
    id = new_id

ob = getattr(context, id)
ob.getContent().edit(mapping=datamodel)

return ob
