<?php

namespace XF\AddOn\DataType;

use XF\Behavior\DevOutputWritable;
use XF\Entity\AddOn;
use XF\Repository\AdminNavigationRepository;

class AdminNavigation extends AbstractDataType
{
	public function getShortName()
	{
		return 'XF:AdminNavigation';
	}

	public function getContainerTag()
	{
		return 'admin_navigation';
	}

	public function getChildTag()
	{
		return 'admin_navigation_entry';
	}

	public function exportAddOnData($addOnId, \DOMElement $container)
	{
		$entries = $this->finder()
			->where('addon_id', $addOnId)
			->order('navigation_id')->fetch();

		foreach ($entries AS $entry)
		{
			$node = $container->ownerDocument->createElement($this->getChildTag());

			$this->exportMappedAttributes($node, $entry);

			$container->appendChild($node);
		}

		return $entries->count() ? true : false;
	}

	public function importAddOnData($addOnId, \SimpleXMLElement $container, $start = 0, $maxRunTime = 0)
	{
		$startTime = microtime(true);

		$entries = $this->getEntries($container, $start);
		if (!$entries)
		{
			return false;
		}

		$ids = $this->pluckXmlAttribute($entries, 'navigation_id');
		$existing = $this->findByIds($ids);

		$i = 0;
		$last = 0;
		foreach ($entries AS $entry)
		{
			$id = $ids[$i++];

			if ($i <= $start)
			{
				continue;
			}

			$entity = $existing[$id] ?? $this->create();

			$entity->setOption('verify_parent', false);
			$entity->getBehavior(DevOutputWritable::class)->setOption('write_dev_output', false);
			$this->importMappedAttributes($entry, $entity);
			$entity->addon_id = $addOnId;

			$entity->save(true, false);

			if ($this->resume($maxRunTime, $startTime))
			{
				$last = $i;
				break;
			}
		}
		return ($last ?: false);
	}

	public function deleteOrphanedAddOnData($addOnId, \SimpleXMLElement $container)
	{
		$this->deleteOrphanedSimple($addOnId, $container, 'navigation_id');
	}

	public function rebuildActiveChange(AddOn $addOn, array &$jobList)
	{
		\XF::runOnce('rebuild_active_' . $this->getContainerTag(), function ()
		{
			/** @var AdminNavigationRepository $repo */
			$repo = $this->em->getRepository(AdminNavigationRepository::class);
			$repo->rebuildNavigationCache();
		});
	}

	protected function getMappedAttributes()
	{
		return [
			'navigation_id',
			'parent_navigation_id',
			'display_order',
			'link',
			'icon',
			'admin_permission_id',
			'debug_only',
			'development_only',
			'hide_no_children',
		];
	}
}
