'Assign the appropriate vehicle & on-shift team to the incident
@ToDo: Specialist teams
@ToDo: Make more generic (currently Porto-specific)'

@staticmethod
def ireport_onaccept(form):

    settings = current.deployment_settings
    if (settings.has_module('fire') and settings.has_module('vehicle')):
        pass
    else:
        return
    db = current.db
    s3db = current.s3db
    vars = form.vars
    ireport = vars.id
    category = vars.category
    if (category == '1100'):
        types = ['VUCI', 'ABSC']
    elif (category == '6102'):
        types = ['VUCI', 'VCOT']
    elif (category == '8201'):
        types = ['VLCI', 'ABSC']
    else:
        types = ['VLCI']
    table = s3db.irs_ireport_vehicle
    stable = s3db.org_site
    atable = s3db.asset_asset
    vtable = s3db.vehicle_vehicle
    ftable = s3db.fire_station
    fvtable = s3db.fire_station_vehicle
    for type in types:
        query = (((((atable.type == s3db.asset_types['VEHICLE']) & (vtable.type == type)) & (vtable.asset_id == atable.id)) & (atable.deleted == False)) & (((table.id == None) | (table.closed == True)) | (table.deleted == True)))
        left = table.on((atable.id == table.asset_id))
        vehicle = db(query).select(atable.id, left=left, limitby=(0, 1)).first()
        if vehicle:
            vehicle = vehicle.id
            query = ((((vtable.asset_id == vehicle) & (fvtable.vehicle_id == vtable.id)) & (ftable.id == fvtable.station_id)) & (stable.id == ftable.site_id))
            site = db(query).select(stable.id, limitby=(0, 1)).first()
            if site:
                site = site.id
            table.insert(ireport_id=ireport, asset_id=vehicle, site_id=site)
            if settings.has_module('hrm'):
                table = s3db.irs_ireport_vehicle_human_resource
                htable = s3db.hrm_human_resource
                on_shift = s3db.fire_staff_on_duty()
                query = (on_shift & (((table.id == None) | (table.closed == True)) | (table.deleted == True)))
                left = table.on((htable.id == table.human_resource_id))
                people = db(query).select(htable.id, left=left, limitby=(0, 5))
                leader = people.first()
                if leader:
                    leader = leader.id
                for person in people:
                    if (person.id == leader.id):
                        table.insert(ireport_id=ireport, asset_id=vehicle, human_resource_id=person.id, incident_commander=True)
                    else:
                        table.insert(ireport_id=ireport, asset_id=vehicle, human_resource_id=person.id)
