class ProgramInstanceRepeatableStageCheck implements Checker {

    @Override
    public ImportSummary check(ImmutableEvent event, WorkContext ctx )
    {
        IdScheme scheme = ctx.getImportOptions().getIdSchemes().getProgramStageIdScheme();
        ProgramStage programStage = ctx.getProgramStage( scheme, event.getProgramStage() );
        ProgramInstance programInstance = ctx.getProgramInstanceMap().get( event.getUid() );
        Program program = ctx.getProgramsMap().get( event.getProgram() );
        TrackedEntityInstance tei = null;
        
        if ( program.isRegistration() )
        {
            tei = ctx.getTrackedEntityInstanceMap().get( event.getUid() ).getLeft();
        }

        /*
         * ProgramInstance should never be null. If it's null, the ProgramInstanceCheck
         * should report this anomaly.
         */
        // @formatter:off
        if ( programInstance != null && 
             tei != null &&
             program.isRegistration() && 
             !programStage.getRepeatable() && 
             hasProgramStageInstance( ctx.getServiceDelegator().getJdbcTemplate(), programStage.getId(), tei.getId() ) )
        {
            return new ImportSummary( ImportStatus.ERROR,
                "Program stage is not repeatable and an event already exists" ).setReference( event.getEvent() )
                    .incrementIgnored();
        }
        // @formatter:on

        return success();
    }

}