<?php
class ChairmanCacheService {
    private $db;
    private $config;
    private $raceService;

    public function __construct(mysqli $db, array $config=array(), ChairmanRaceService $raceService=null) {
        $this->db = $db;
        $this->config = $config;
        $this->raceService = $raceService;
    }

    public function buildCache($raceDate, $venue='', $raceNum=0) {
        $cacheDir = isset($this->config['cache_dir']) ? $this->config['cache_dir'] : dirname(__DIR__) . '/cache';
        if(!is_dir($cacheDir)) @mkdir($cacheDir, 0775, true);

        $payload = $this->raceService->getAnalysisPayload($raceDate,$venue,$raceNum);
        $payload['cache_built_at'] = date('c');
        $payload['cache_type'] = 'CHAIRMAN_TODAY_CACHE_V13';

        $file = $cacheDir . '/' . chairman_cache_filename($raceDate,$venue,$raceNum);
        file_put_contents($file, json_encode($payload, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT));

        return array(
            'file'=>$file,
            'public_file'=>chairman_public_path($file, $this->config),
            'bytes'=>file_exists($file)?filesize($file):0,
            'payload'=>$payload
        );
    }

    public function readCache($raceDate, $venue='', $raceNum=0) {
        $cacheDir = isset($this->config['cache_dir']) ? $this->config['cache_dir'] : dirname(__DIR__) . '/cache';
        $file = $cacheDir . '/' . chairman_cache_filename($raceDate,$venue,$raceNum);
        if(!file_exists($file)) return null;
        return array(
            'file'=>$file,
            'public_file'=>chairman_public_path($file, $this->config),
            'bytes'=>filesize($file),
            'payload'=>json_decode(file_get_contents($file),true)
        );
    }
}
