<?php
class ProductionEngine {
    private $rankingEngine;
    private $decisionEngine;
    private $optimizerRepo;
    private $events;

    public function __construct(RankingEngine $rankingEngine, DecisionEngine $decisionEngine, OptimizerRepository $optimizerRepo, ChairmanEventDispatcher $events=null) {
        $this->rankingEngine = $rankingEngine;
        $this->decisionEngine = $decisionEngine;
        $this->optimizerRepo = $optimizerRepo;
        $this->events = $events;
    }

    public function run($raceDate, $venue='', $raceNum=0) {
        if($this->events) $this->events->dispatch('ProductionStarted', compact('raceDate','venue','raceNum'));
        $ranking = $this->rankingEngine->ranking($raceDate,$venue,$raceNum);
        $summary = $this->optimizerRepo->summaries($raceDate,$venue,$raceNum);
        $decision = $this->decisionEngine->decide($ranking);
        if($this->events) $this->events->dispatch('DecisionFinished', array('races'=>count($decision),'horses'=>count($ranking)));

        return array(
            'status'=>'OK',
            'engine_version'=>'2.0',
            'race_date'=>$raceDate,
            'venue'=>$venue,
            'race_num'=>chairman_i($raceNum),
            'summary'=>$summary,
            'ranking'=>$ranking,
            'decision'=>$decision,
            'events'=>$this->events ? $this->events->all() : array(),
            'generated_at'=>date('c')
        );
    }
}
