<?php

namespace Velis;

use Velis\Model\DataObject;
use Velis\Model\Sanitizable;

/**
 * Cron log model
 *
 * @author Robert Jamróz <robert.jamroz@velis.pl>
 */
class CronLog extends DataObject implements Sanitizable
{
    protected static $_filterListParams = true;

    /**
     * @return string
     */
    protected function _getTableName(): string
    {
        return 'app.cron_log_tab';
    }


    /**
     * Returns task name
     * @return string
     */
    public function getName(): string
    {
        return $this['job_name'];
    }

    /**
     * {@inheritDoc}
     */
    public static function getList($page = 1, $params = null, $order = null, $limit = self::ITEMS_PER_PAGE, $fields = null): array
    {
        if ($params['search']) {
            self::$_listConditions[] = '(job_name ILIKE :search OR info ILIKE :search)';
            self::$_listParams['search'] = '%' . addslashes($params['search']) . '%';
        }

        if ($params['date_started_from']) {
            self::$_listConditions[] = 'date_started >= :date_started_from';
            self::$_listParams['date_started_from'] = $params['date_started_from'] . ' 00:00:00';
        }

        if ($params['date_started_to']) {
            self::$_listConditions[] = 'date_started <= :date_started_to';
            self::$_listParams['date_started_to'] = $params['date_started_to'] . ' 23:59:59';
        }

        return parent::getList($page, $params, $order, $limit);
    }

    /**
     * @return string[]
     */
    public static function getJobNames(): array
    {
        if (!isset(App::$cache['cronLogJobNames'])) {
            $query = '
                SELECT DISTINCT ON (job_name) job_name
                FROM app.cron_log_tab
            ';

            $names = self::$_db->getAll($query);
            $value = [];

            foreach ($names as $name) {
                $value[$name['job_name']] = $name['job_name'];
            }

            App::$cache['cronLogJobNames'] = $value;
        }

        return App::$cache['cronLogJobNames'];
    }

    /**
     * @return string[]
     */
    public static function getJobStatuses(): array
    {
        if (!isset(App::$cache['cronLogJobStatuses'])) {
            $query = '
                SELECT DISTINCT ON (status) status
                FROM app.cron_log_tab
            ';

            $names = self::$_db->getAll($query);
            $value = [];

            foreach ($names as $name) {
                $value[$name['status']] = $name['status'];
            }

            App::$cache['cronLogJobStatuses'] = $value;
        }

        return App::$cache['cronLogJobStatuses'];
    }
}
