'Registration onaccept: track status changes, update
shelter population
@param form: the FORM (also accepts Row)'

@classmethod
def shelter_registration_onaccept(cls, form):

    try:
        if (type(form) is Row):
            formvars = form
        else:
            formvars = form.vars
        registration_id = formvars.id
    except AttributeError:
        unit_id = None
    else:
        unit_id = formvars.get('shelter_unit_id')
        if registration_id:
            s3db = current.s3db
            db = current.db
            rtable = s3db.cr_shelter_registration
            query = ((rtable.id == registration_id) & (rtable.deleted != True))
            reg = db(query).select(rtable.id, rtable.shelter_id, rtable.shelter_unit_id, rtable.registration_status, rtable.check_in_date, rtable.check_out_date, rtable.modified_on, rtable.person_id, limitby=(0, 1)).first()
            if reg:
                person_id = reg.person_id
                unit_id = reg.shelter_unit_id
                htable = s3db.cr_shelter_registration_history
                query = (((htable.person_id == person_id) & (htable.shelter_id == reg.shelter_id)) & (htable.deleted != True))
                row = db(query).select(htable.status, htable.date, orderby=(~ htable.created_on), limitby=(0, 1)).first()
                if row:
                    previous_status = row.status
                    previous_date = row.date
                else:
                    previous_status = None
                    previous_date = None
                current_status = reg.registration_status
                if (current_status == 2):
                    effective_date_field = 'check_in_date'
                elif (current_status == 3):
                    effective_date_field = 'check_out_date'
                else:
                    effective_date_field = None
                if effective_date_field:
                    effective_date = reg[effective_date_field]
                else:
                    effective_date = reg.modified_on
                if ((current_status != previous_status) or (effective_date_field and (not effective_date))):
                    if effective_date_field:
                        if ((effective_date_field not in formvars) or (not effective_date) or (previous_date and (effective_date < previous_date))):
                            effective_date = current.request.utcnow
                            reg.update_record(**{effective_date_field: effective_date})
                    htable.insert(previous_status=previous_status, status=current_status, date=effective_date, person_id=person_id, shelter_id=reg.shelter_id)
                    if current.deployment_settings.has_module('dvr'):
                        s3db.dvr_update_last_seen(person_id)
    cls.shelter_population_onaccept(form, tablename='cr_shelter_registration', unit_id=unit_id)
