<?php

namespace CleantalkSP\SpbctWP\FSWatcher;

use CleantalkSP\SpbctWP\FSWatcher\Repository\FileRepository;
use CleantalkSP\SpbctWP\FSWatcher\Storage\FileStorage;

class Service
{
    public static function setStorage($storage = 'file')
    {
        switch ($storage) {
            case 'file':
            default:
                Controller::$storage = FileStorage::class;
                break;
            // case 'customdb':
            // Controller::$storage = CustomDBStorage::class;
            // Controller::$repository = CustomDBStorage::class;
            // break;
            // case 'db':
            // Controller::$storage = DBStorage::class;
            // Controller::$repository = DBStorage::class;
            // break;
        }
    }

    /**
     * Set snapshots to completed status
     *
     * @return void
     */
    public static function setAllJournalsAsCompleted()
    {
        $storage = Controller::$storage;
        $storage::setAllJournalsAsCompleted();
    }

    public static function isRateLimitPass()
    {
        $time = time();

        $rateLimit = get_option('spbc_rate_limit_fswatcher', [
            'limit' => 30,
            'expires_in' => $time + 60,
            'attempts' => 0,
        ]);

        if ($rateLimit['expires_in'] <= $time) {
            $rateLimit['expires_in'] = $time + 60;
            $rateLimit['attempts'] = 0;
        }

        if ($rateLimit['expires_in'] > $time) {
            $rateLimit['attempts']++;
        }

        if ($rateLimit['attempts'] >= $rateLimit['limit']) {
            return false;
        }

        update_option('spbc_rate_limit_fswatcher', $rateLimit);

        return true;
    }
}
