<?php

namespace WpieFw\Settings\Iterator;

use WpieFw\Framework\Patterns\Iterator\WpieCollection;
use WpieFw\Settings\Iterator\WpieAbstractSetting;
use WpieFw\Exceptions\WpieInvalidArgumentException;

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

final class WpieSettingsCollection extends WpieCollection
{
	public function __construct( array $collection = [] )
	{
		parent::__construct( $collection );
	}

	/**
	 * @param string $offset
	 * @param WpieAbstractSetting $value
	 */
	public function offsetSet( $offset, $value ): void
	{
		if( '' === trim( $offset ) ) {
			throw new WpieInvalidArgumentException( 'Cannot add setting to collection. Index is empty.' );
		}
		if( !$value instanceof WpieAbstractSetting ) {
			throw new WpieInvalidArgumentException( 'Cannot add setting to collection. Value is not a WpieAbstractSetting instance.' );
		}

		$this->collection[$offset] = $value;
	}

	/**
	 * Get all setting names
	 *
	 * @return NULL[]
	 */
	public function getSettingNames()
	{
		$names = [];

		foreach ( $this as $setting ) {
			$names[] = $setting->getName();
		}

		return $names;
	}

	/**
	 * Get the first item of the collection
	 *
	 * @uses self::getSettingNames()
	 *
	 * @since 2.0.5
	 *
	 * @return string
	 */
	public function getFirstSettingName()
	{
		if( $this->hasCollection() ) {
			return array_slice($this->getSettingNames(), 0, 1);
		} else {
			return '';
		}
	}

	/**
	 * Get the first item of the collection
	 *
	 * @uses self::getFirstSettingName()
	 *
	 * @since 2.0.5
	 *
	 * @return WpieSetting|bool a WpieSetting instance or false with no collection
	 */
	public function getFirstSetting()
	{
		if( $this->hasCollection() ) {
			return $this->get($this->getFirstSettingName());
		} else {
			return false;
		}
	}
}