<?php

namespace CleantalkSP\SpbctWP\Scanner\OSCron\Storages;

use CleantalkSP\SpbctWP\Scanner\OSCron\Objects\OSCronTask;
use CleantalkSP\SpbctWP\Scanner\OSCron\View\OSCronLocale;

class OsCronTasksStorage
{
    /**
     * @var string The name of the option to store tasks.
     */
    private static $tasks_storage_name = 'spbc_oscron_tasks';

    /**
     * Saves the tasks to storage.
     *
     * @param OSCronTask[] $tasks The tasks to save.
     */
    public static function set($tasks)
    {
        update_option(static::$tasks_storage_name, $tasks);
    }

    /**
     * Retrieves the tasks from storage.
     *
     * @return OSCronTask[] The tasks from storage.
     */
    public static function get()
    {
        $tasks = get_option(static::$tasks_storage_name, []);

        if (is_null($tasks) || false === $tasks) {
            return array();
        }

        return $tasks;
    }

    /**
     * Retrieves a task by its unique identifier.
     *
     * @param string $uid The unique identifier of the task.
     * @return OSCronTask|false The task if found, false otherwise.
     * @throws \Exception If an error occurs during retrieval.
     */
    public static function getById($uid)
    {
        $tasks = static::get();
        foreach ($tasks as $task) {
            if ($task->id === $uid) {
                return $task;
            }
        }
        return false;
    }

    /**
     * Get count of dangerous tasks.
     * @return int
     */
    public static function getCountOfDangerousTasks()
    {
        $count = 0;
        $tasks = static::get();
        foreach ($tasks as $task) {
            if ($task->status === 'dangerous') {
                $count++;
            }
        }
        return $count;
    }


    /**
     * Retrieves the tasks from storage as an array.
     *
     * @return array The tasks from storage as an array.
     */
    public static function getAsArray()
    {
        global $spbc;
        $tasks = static::get();
        $result_array = array();
        foreach ($tasks as $task) {
            if ($task instanceof OSCronTask) {
                $result_array[] = $task->getArray();
            } else {
                $spbc->error_add('', OSCronLocale::getInstance()->error__load_cron_storage);
            }
        }
        return $result_array;
    }
}
