'Shelter inspection flag onaccept:
- auto-create task if/as configured'

@staticmethod
def shelter_inspection_flag_onaccept(form):

    settings = current.deployment_settings
    if (not settings.get_cr_shelter_inspection_tasks()):
        return
    formvars = form.vars
    try:
        record_id = formvars.id
    except AttributeError:
        return
    db = current.db
    s3db = current.s3db
    table = s3db.cr_shelter_inspection_flag
    ftable = s3db.cr_shelter_flag
    itable = s3db.cr_shelter_inspection
    utable = s3db.cr_shelter_unit
    ltable = s3db.cr_shelter_inspection_task
    ttable = s3db.project_task
    join = (itable.on((itable.id == table.inspection_id)), utable.on((utable.id == itable.shelter_unit_id)), ftable.on((ftable.id == table.flag_id)))
    left = ltable.on((ltable.inspection_flag_id == table.id))
    query = (table.id == record_id)
    row = db(query).select(table.id, table.flag_id, ftable.create_task, ftable.task_description, ftable.task_priority, ftable.task_assign_to, ltable.task_id, itable.shelter_unit_id, utable.name, join=join, left=left, limitby=(0, 1)).first()
    if (not row):
        return
    create_task = False
    create_link = None
    flag = row.cr_shelter_flag
    task_description = flag.task_description
    task_priority = flag.task_priority
    task_assign_to = flag.task_assign_to
    shelter_unit = row.cr_shelter_unit.name
    if flag.create_task:
        inspection_task = row.cr_shelter_inspection_task
        if (inspection_task.task_id is None):
            shelter_unit_id = row.cr_shelter_inspection.shelter_unit_id
            flag_id = row.cr_shelter_inspection_flag.flag_id
            active_statuses = settings.get_cr_shelter_inspection_task_active_statuses()
            left = (itable.on((itable.id == table.inspection_id)), ltable.on((ltable.inspection_flag_id == table.id)), ttable.on((ttable.id == ltable.task_id)))
            query = (((((((table.flag_id == flag_id) & (table.deleted == False)) & (ttable.name == task_description)) & ttable.status.belongs(active_statuses)) & (ttable.deleted == False)) & (itable.shelter_unit_id == shelter_unit_id)) & (itable.deleted == False))
            row = db(query).select(ttable.id, left=left, limitby=(0, 1)).first()
            if row:
                create_link = row.id
            else:
                create_task = True
    if create_task:
        task = {'name': ('%s:    %s' % (shelter_unit, task_description)), 'priority': task_priority, 'pe_id': task_assign_to}
        task_id = ttable.insert(**task)
        if task_id:
            task['id'] = task_id
            s3db.update_super(ttable, task)
            auth = current.auth
            auth.s3_set_record_owner(ttable, task_id)
            auth.s3_make_session_owner(ttable, task_id)
            s3db.onaccept(ttable, task, method='create')
            create_link = task_id
    if create_link:
        ltable.insert(inspection_flag_id=record_id, task_id=create_link)
