<?php

namespace App\Rules;

use Illuminate\Contracts\Validation\Rule;

class Interval implements Rule
{

    // 5m, 15m, 30m, 1h, 2h, 6h, 12h, 24h and 48h - the windows offered by the
    // usage chart endpoints, which receive their `time` input in seconds.
    public const USAGE_CHART = [5, 15, 30, 60, 120, 360, 720, 1440, 2880];

    private $minutes = [];

    public function __construct(array $_minutes)
    {
        $this->minutes = $_minutes;
    }

    public static function make(array $minutes)
    {
        return new static($minutes);
    }


    public function passes($attribute, $value)
    {
        // The value is a duration in seconds; it must land exactly on one of
        // the configured minute durations.
        if (!is_int($value) && !(is_string($value) && preg_match('/^\d+$/', $value))) {
            return false;
        }

        $seconds = (int) $value;

        return $seconds % 60 === 0 && in_array($seconds / 60, $this->minutes, true);
    }

    public function message()
    {
        return 'The :attribute must be one of the permitted intervals.';
    }
}
