<?php
/*
** Copyright (C) 2021-2026 initMAX s.r.o.
**
** 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/>.
**/


namespace Modules\TetrisMAX\Actions\Widgets;

use CWidgetFieldRadioButtonList;
use CWidgetForm;
use Modules\TetrisMAX\Includes\Speed;
use Modules\TetrisMAX\Services\WidgetTranslator;

/**
 * v1 (Zabbix 6.0/6.2) tetrisMAX widget form.
 *
 * ONE PRODUCT: this mirrors the manifest-v2 form (includes/WidgetForm.php)
 * field for field - same field NAME, same option VALUES, same default - so a
 * dashboard configured on 6.0 opens unchanged after an upgrade to 7.4 and
 * back. A stored `speed = 2` means FAST on every line. The only difference is
 * the v1 CWidgetField* class, which has a different constructor and no
 * addField() on the form.
 *
 * Nothing is faked and nothing is left out: the game asks Zabbix for nothing
 * that 6.0 cannot give, so the two forms carry exactly the same control.
 */
class tetrisMAXForm extends CWidgetForm {

	const WIDGET_TYPE = 'tetrismax';

	public function __construct($data, $templateid) {
		parent::__construct($data, $templateid, static::WIDGET_TYPE);

		// setModern: 6.4+ renders this as a segmented control
		// (CWidgetFieldRadioButtonListView calls setModern() itself), while the
		// v1 default is a column of plain radios. Same control, same look.
		$this->addWidgetField(
			(new CWidgetFieldRadioButtonList('speed', WidgetTranslator::translate('form.speed.label'), [
				Speed::SLOW => WidgetTranslator::translate('form.speed.option.slow'),
				Speed::NORMAL => WidgetTranslator::translate('form.speed.option.normal'),
				Speed::FAST => WidgetTranslator::translate('form.speed.option.fast')
			]))
				->setModern(true)
				->setDefault(Speed::NORMAL)
		);
	}

	/**
	 * Register a field, taking its stored value first.
	 *
	 * 6.0/6.2's CWidgetForm has no addField() - the v2 API added it - so the
	 * form fills $this->fields itself. Named addWidgetField so a future core
	 * addField() cannot silently change what this calls.
	 */
	private function addWidgetField($field): void {
		if (array_key_exists($field->getName(), $this->data)) {
			$field->setValue($this->data[$field->getName()]);
		}

		$this->fields[$field->getName()] = $field;
	}
}
