<?php
/*
** Copyright (C) 2001-2026 Zabbix SIA
**
** This program is free software: you can redistribute it and/or modify it under the terms of
** the GNU Affero General Public License as published by the Free Software Foundation, version 3.
**
** 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 Affero General Public License for more details.
**
** You should have received a copy of the GNU Affero General Public License along with this program.
** If not, see <https://www.gnu.org/licenses/>.
**/


/**
 * A parser for a list of time periods separated by a semicolon.
 */
class CTimePeriodsParser extends CParser {

	private CTimePeriodParser $time_period_parser;

	private array $periods_parts = [];
	private array $options = ['usermacros' => false];

	public function __construct($options = []) {
		if (array_key_exists('usermacros', $options)) {
			$this->options['usermacros'] = $options['usermacros'];
		}

		$this->time_period_parser = new CTimePeriodParser(['usermacros' => $this->options['usermacros']]);
	}

	/**
	 * Parse the given periods separated by a semicolon.
	 *
	 * @param string $source  Source string that needs to be parsed.
	 * @param int    $pos     Position offset.
	 */
	public function parse($source, $pos = 0) {
		$this->length = 0;
		$this->match = '';
		$this->periods_parts = [];

		$periods_parts = [];
		$p = $pos;
		$offset = 0;

		while (isset($source[$p + $offset])) {
			if ($this->time_period_parser->parse($source, $p + $offset) == self::PARSE_FAIL) {
				break;
			}

			$p += $offset + $this->time_period_parser->getLength();
			$periods_parts[$this->time_period_parser->getMatch()] = $this->time_period_parser->getPeriodParts();

			if (isset($source[$p]) && $source[$p] !== ';') {
				break;
			}

			$offset = 1;
		}

		if ($p == $pos || isset($source[$p])) {
			return self::PARSE_FAIL;
		}

		$this->length = $p - $pos;
		$this->match = substr($source, $pos, $this->length);
		$this->periods_parts = $periods_parts;

		return self::PARSE_SUCCESS;
	}

	/**
	 * Retrieve the time parts for periods.
	 *
	 * @return array
	 */
	public function getPeriodsParts(): array {
		return $this->periods_parts;
	}
}
