<?php

/*
 * YamlMempoolsDiscovery.php
 *
 * -Description-
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <https://www.gnu.org/licenses/>.
 *
 * @package    LibreNMS
 * @link       https://www.librenms.org
 * @copyright  2025 Tony Murray
 * @author     Tony Murray <murraytony@gmail.com>
 */

namespace LibreNMS\OS\Traits;

use App\Models\Mempool;
use LibreNMS\Discovery\Yaml\IndexField;
use LibreNMS\Discovery\Yaml\LiteralField;
use LibreNMS\Discovery\Yaml\OidField;
use LibreNMS\Discovery\Yaml\YamlDiscoveryField;
use LibreNMS\Discovery\YamlDiscoveryDefinition;

trait YamlMempoolsDiscovery
{
    public function discoverYamlMempools(): \Illuminate\Support\Collection
    {
        $mempools_yaml = $this->getDiscovery('mempools');

        $def = YamlDiscoveryDefinition::make(Mempool::class)
            ->addField(new IndexField('index', 'mempool_index'))
            ->addField(new LiteralField('type', 'mempool_type', $this->getName()))
            ->addField(new LiteralField('class', 'mempool_class', 'system'))
            ->addField(new YamlDiscoveryField('precision', 'mempool_precision', 1))
            ->addField(new YamlDiscoveryField('descr', 'mempool_descr', 'Memory', callback: fn ($value) => ucwords((string) $value)))
            ->addField(new OidField('used', 'mempool_used'))
            ->addField(new OidField('free', 'mempool_free', should_poll: fn (YamlDiscoveryDefinition $def) => ($def->getFieldCurrentValue('used') === null || $def->getFieldCurrentValue('total') === null) && is_numeric($def->getFieldCurrentValue('free'))))
            ->addField(new OidField('total', 'mempool_total', should_poll: false))
            ->addField(new OidField('percent_used', 'mempool_perc'))
            ->addField(new YamlDiscoveryField('warn_percent', 'mempool_perc_warn', 90))
            ->afterEach(function (Mempool $mempool, YamlDiscoveryDefinition $def, $yaml, $index): void {
                // fill missing values
                $mempool->fillUsage($mempool->mempool_used, $mempool->mempool_total, $mempool->mempool_free, $mempool->mempool_perc);
            });

        return $def->discover($mempools_yaml);
    }
}
