<?php

class TemplateTest extends \PHPUnit\Framework\TestCase
{
	use \Dalten\TestHelper\DomDocumentTestTrait;

	private $_data = array(
		'zeroAsNumber' => 0,
		'zeroAsString' => '0',
		'OK' => 'OK',
		'emptyString' => ''
	);

	private function _fillTemplateAndReturnXmlText(Dalten_Xml_Template_Node $template)
	{
		$simpleXml = new Dalten_Xml_SimpleXml(
			'<?xml version="1.0" encoding="UTF-8" ?><test/>'
		);
		$template->fill($simpleXml, $this->_data);

		return $simpleXml->asXML();
	}

	public function testZeroIsRemoved()
	{
		$template = new Dalten_Xml_Template_Root('test');
		$template->addElement('zeroElementN', 'zeroAsNumber');
		$template->addElement('zeroElementS', 'zeroAsString');
		$template->addAttribute('zeroAttributeN', 'zeroAsNumber');
		$template->addAttribute('zeroAttributeS', 'zeroAsString');

		$xml = $this->_fillTemplateAndReturnXmlText($template);

		$this->assertSelectCount('zeroElementN', 0, $xml, 'Nefunguje schovani ciselne nulovych elementu.', false);
		$this->assertSelectCount('zeroElementS', 0, $xml, 'Nefunguje schovani textove nulovych elementu.', false);
		$this->assertSelectCount('zeroAttributeN', 0, $xml, 'Nefunguje schovani ciselne nulovych atributu.', false);
		$this->assertSelectCount('zeroAttributeS', 0, $xml, 'Nefunguje schovani textove nulovych atributu.', false);
	}

	public function testpreserveZeros()
	{
		$template = new Dalten_Xml_Template_Root('test');
		$template->addElement('preservedZero', 'zeroAsNumber')->zeroIsEmpty(false);
		$template->addElement('unpreservedZero', 'zeroAsNumber')->zeroIsEmpty(true);

		$xml = $this->_fillTemplateAndReturnXmlText($template);

		$this->assertSelectCount('preservedZero', 1, $xml, 'Nefunguje ochrana nulovych elementu.', false);
		$this->assertSelectCount(
			'unpreservedZero', 0, $xml, 'Nefunguje vynucene schovani ciselne nulovych elementu.', false
		);
	}

	public function testFungujeForcedPresence()
	{
		$template = new Dalten_Xml_Template_Root('test');
		$template->addElement('mustBeHere')->forcedPresence();

		$xml = $this->_fillTemplateAndReturnXmlText($template);

		$this->assertSelectCount('mustBeHere', 1, $xml, 'Nefunguje ochrana nulovych elementu.', false);
	}

	public function testFungujiKontroly()
	{
		$testData = array(
			'tooLong' => 'looooooooong',
			'blacklisted' => 'black'
		);
		$template = new Dalten_Xml_Template_Element('test');
		$template->addElement('missing', 'missingVariable')->required('missing');
		$template->addElement('toolong', 'tooLong')->maxLen(1, 'maxlen');
		$template->addElement('whitelist', 'blacklisted')->whitelistCheck(array('white'), 'whitelist');
		$verificationResult = $template->verify($testData);

		$this->assertContains('missing', $verificationResult, 'Nefunguje hledani chybejicih povinych elementu.', false);
		$this->assertContains('maxlen', $verificationResult, 'Nefunguje omezeni na maximalni delku.', false);
		$this->assertContains('whitelist', $verificationResult, 'Nefunguje omezeni na whitelist.', false);
	}
}
