<?php
/**
 * @package CleverOgre
 * @subpackage OgreAlert
 * @since OgreAlert 0.1.7
 */

namespace OgreAlert;

if (!defined('ABSPATH')) exit;

class Priority {

    private static $priorities = [
        'high',
        'normal',
        'low',
    ];

    public static function load() {
        add_filter('ogrealert/get_active', [__CLASS__, 'order'], 10, 1);
    }

    static function order($alerts) {
        if (!is_array($alerts) || empty($alerts)) return $alerts;

        $_alerts = [];
        foreach ($alerts as $id) {
            $_alerts[] = [
                'id' => $id,
                'priority' => self::get($id),
            ];
        }

        usort($_alerts, function ($a, $b) {
            return array_search($a['priority'], self::$priorities) > array_search($b['priority'], self::$priorities);
        });

        return wp_list_pluck($_alerts, 'id');
    }

    public static function get($id) {
        if (!\OgreAlert\Alert::valid($id)) return false;

        $value = get_post_meta($id, '_ogrealert_priority', true);
        if (!$value || !in_array($value, self::$priorities)) {
            $value = 'normal';
        }

        return $value;
    }

}

\OgreAlert\Priority::load();
