<?php

namespace WpieFw\Settings\Iterator;

use WpieFw\Settings\WpieSettingsValues;
use WpieFw\Settings\Iterator\WpieAbstractSetting;
use WpieFw\Settings\Parser\WpieAbstractSettingsParser;

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

final class WpieSetting extends WpieAbstractSetting
{
	/**
	 * Constructor
	 *
	 * @param string $idx
	 * @param WpieAbstractSettingsParser $parser
	 * @param WpieSettingsValues $values
	 *
	 * @uses parent::__construct();
	 */
	public function __construct( string $idx, WpieAbstractSettingsParser $parser, WpieSettingsValues $values )
	{
		parent::__construct( $idx, $parser, $values );
	}

	/**
	 * Declare the stack
	 *
	 * @uses self::getDefaults()
	 */
	public function initStack()
	{
		if( $this->isNew ) {
			// set the default values as the stack
			$this->stack = $this->getDefaults();
			// add meta data to the stack
			$this->stack[self::IDX] = $this->idx;
			$this->stack[self::PRIO] = $this->priority;
			$this->stack[self::IS_DEFAULT] = $this->isDefault;
			// the new stack must be saved
			$this->dataToPersist = $this->stack;
		} else {
			if( $this->isLanguaged ) {
				$this->stack = $this->stored[$this->firstLocale];
				$this->dataToPersist = $this->stack;
				$this->isLanguaged = false;
			} else {
				$this->stack = $this->stored;
			}
			// get meta data from the stack
			$this->priority = ( isset( $this->stack[self::PRIO] ) ) ? $this->stack[self::PRIO] : $this->priority;
			$this->isDefault = ( isset( $this->stack[self::IS_DEFAULT] ) ) ? $this->stack[self::IS_DEFAULT] : $this->isDefault;
		}
	}

	/**
	 * @param string $key
	 * @param mixed $value
	 * @param bool $persist
	 * @return \WpieFw\Settings\Iterator\WpieSetting
	 */
	public function set( string $key, $value, bool $persist = false )
	{
		$this->stack[$key] = $value;

		if( $persist ) {
			$this->persist();
		}

		return $this;
	}

	/**
	 * Merge the current stack with a temporary backup stack
	 *
	 * @param array $backup
	 *
	 * @uses array_merge
	 */
	protected function doMergeSettingsTmp( array $backup = [] )
	{
		$merged = array_merge( $this->stack, $backup );

		$this->stack = $merged;
		$this->dataToPersist = $merged;
	}
}