'Ensure that Skills are Populated from Certifications
- called both onaccept & ondelete'

@staticmethod
def hrm_certification_onaccept(record):

    try:
        certification_id = record.vars.id
    except:
        certification_id = record.id
    db = current.db
    table = db.hrm_certification
    data = table((table.id == certification_id))
    try:
        if data.deleted:
            deleted_fk = json.loads(record.deleted_fk)
            person_id = deleted_fk['person_id']
        else:
            person_id = data['person_id']
    except:
        return
    ctable = db.hrm_competency
    cstable = db.hrm_certificate_skill
    query = ((ctable.person_id == person_id) & (ctable.from_certification == True))
    db(query).delete()
    query = (((table.person_id == person_id) & (table.certificate_id == cstable.certificate_id)) & (cstable.skill_id == db.hrm_skill.id))
    certifications = db(query).select()
    for certification in certifications:
        skill = certification['hrm_skill']
        cert = certification['hrm_certificate_skill']
        query = ((ctable.person_id == person_id) & (ctable.skill_id == skill.id))
        existing = db(query).select()
        better = True
        for e in existing:
            if (e.competency_id.priority > cert.competency_id.priority):
                db((ctable.id == e.id)).delete()
            else:
                better = False
                break
        if better:
            ctable.update_or_insert(person_id=person_id, competency_id=cert.competency_id, skill_id=skill.id, comments='Added    by    certification', from_certification=True)
