<?php
namespace App\Bsp\HotUA;

class HOTBase extends \App\Utils\BaseParser\TextParser\BlockRegexpAbstract
{
	protected $extractRegexp = "/^(?P<rawData>.+)/";

	/**
	 * (non-PHPdoc)
	 * @see \App\Utils\BaseParser\TextParser\BlockAbstract::createObject()
	 */
	public function createObject($type, $options, $self)
	{
		if(!isset($options['req'])) {
			$options['req'] = true;
		}

		$class = sprintf("\App\Bsp\HotUA\Lines\Types\%s", $type);
		if (class_exists($class)) {
			return new $class($options, $self);
		}

		return parent::createObject($type, $options, $self);
	}

	/**
	 * (non-PHPdoc)
	 * @see \App\Utils\BaseParser\TextParser\BlockRegexpAbstract::isValid()
	 */
	public function isValid() {
		if ($this->children[0]['type']=='Constant' && $this->children[0]['val']) {
			$regexp = [];
			foreach($this->children as $child) {
				if ($child['type']=='Constant') {
					$regexp[]= sprintf("(%s)", preg_quote($child['val'], "/"));
				}
				elseif($child['len']) {
					$regexp[]= sprintf("(.{%d})", $child['len']);
				}
				else {
					break;	// stop on fields without length
				}
			}

			$regexpStr = implode('', $regexp);
			$regexpStr = preg_replace("/(\(\.\{[0-9]+\}\))+$/", "", $regexpStr);	// remove repeating non-constant fields from the end of the string

			$m = $this->safeMatch("/^{$regexpStr}/", $this->rawData);
			return (bool)$m->count;
		}
		else {
			$m = $this->safeMatch($this->extractRegexp, $this->rawData);
			return (bool)$m->count;
		}
	}

	/**
	 * helper function, parser all PriceAmount lines and converts them to a real float number
	 */
	protected function postProcessPriceAmount($ret, $children, $decimals)
	{
		foreach($children as $chld) {
			if ($chld['type']=='PriceAmount') {
				$ret->extractedData[$chld['key']] = (float)$ret->extractedData[$chld['key']]/pow(10, $decimals);
			}
		}

		return $ret;
	}
}
