<?php

namespace Planaday\Utility\FormBuilder\Structures;

use Planaday\Utility\FormBuilder\Filterable;
use Planaday\Utility\FormBuilder\LayoutItem;
use Planaday\Utility\FormBuilder\Structure;

class TabbedGroups implements Structure{
	use BasicStructure;

	protected ?string $index = null;
	protected array $tabs = [];

	public function setIndex( ?string $index ): self {
		$this->index = $index;
		return $this;
	}

	public function getIndex(): ?string {
		return $this->index;
	}

	public function addContents( ...$contents ): static {
		return $this->addTab('', ...$contents);
	}

	public function addTab(string $tabName, ...$contents ): self {
		foreach ($contents as $content) {
			$content->setParent($this);
			$this->contents[] = $content;
		}

		$this->tabs[] = [
			"label" => $tabName,
			"contents" => $contents,
			"isActive" => true
		];
		return $this;
	}

	public function applyFilter( array $filters ): ?bool {
		$shouldStay = null;

		if ($this->index !== null) {
			$filters = $filters[$this->index] ?? [];
		}

		foreach ($this->tabs as $tab) {
			$tabShouldStay = null;
			foreach ($tab["contents"] as $content){
				if ($content instanceof Filterable) {
					$itemShown = $content->applyFilter($filters);
					if ($itemShown !== null) {
						$tabShouldStay = $itemShown || ($tabShouldStay ?? false);
					}
				}
			}

			$tab["isActive"] = $tabShouldStay ?? true;
			if ($tabShouldStay !== null) {
				$shouldStay = $tabShouldStay || ($shouldStay ?? false);
			}
		}

		$this->isActive = $shouldStay ?? true;
		return $shouldStay;
	}

	protected function getFilteredTabs(): array {
		$filteredTabs = [];

		foreach ($this->tabs as $tab) {
			if (!$tab["isActive"]) {
				continue;
			}

			$filteredTab = [
				"label" => $tab["label"],
				"contents" => [],
			];
			/** @var LayoutItem $content */
			foreach ($tab["contents"] as $content) {
				if (!$content instanceof Filterable || $content->isPastFilter()) {
					$filteredTab["contents"][] = $content->getItemId();
				}
			}
			if (count($filteredTab["contents"]) === 0) {
				continue;
			}
			$filteredTabs[] = $filteredTab;
		}

		return $filteredTabs;
	}

	public function getImplJson(): array {
		return [
			"type" => 'tabbedGroups',
			"tabs" => $this->getFilteredTabs(),
		];
	}
}