<?php

namespace KupShop\PohodaBundle\Utils\Tools;

use KupShop\KupShopBundle\Util\System\BundleFinder;
use KupShop\PohodaBundle\Exceptions\PohodaException;
use KupShop\PohodaBundle\Utils\PohodaConnector;

class TransformHelper
{
    /**
     * @var BundleFinder
     */
    private $bundleFinder;

    /**
     * @var PohodaConnector
     */
    private $pohodaConnector;

    public function __construct(BundleFinder $bundleFinder, PohodaConnector $pohodaConnector)
    {
        $this->bundleFinder = $bundleFinder;
        $this->pohodaConnector = $pohodaConnector;
    }

    /**
     * @return false|string
     *
     * @throws PohodaException
     */
    public function loadXslt($filename)
    {
        $folders = array_reverse($this->bundleFinder->getBundlesPath('Resources/xslt/'));

        if ($this->pohodaConnector && ($config = $this->pohodaConnector->getCurrent())) {
            $serverIndex = $this->pohodaConnector->getCurrentKey();
            $mFilename = str_replace('.xsl', "{$serverIndex}.xsl", $filename);

            if ($content = $this->loadContentFromFile($folders, $mFilename)) {
                return $content;
            }
        }

        if ($content = $this->loadContentFromFile($folders, $filename)) {
            return $content;
        }

        throw new PohodaException("Missing {$filename} transform file!");
    }

    public function loadContentFromFile($folders, $filename)
    {
        foreach ($folders as $folder) {
            if (file_exists($folder.$filename)) {
                return file_get_contents($folder.$filename);
            }
        }

        return false;
    }

    /**
     * @param $sourceXml string
     * @param $xslt      string
     *
     * @return \DOMDocument|false
     */
    public function baseTransform($sourceXml, $xslt)
    {
        $xmlDOMResponse = new \DOMDocument();
        $xmlDOMResponse->loadXML($sourceXml);

        $XSLTransformation = new \DOMDocument();
        $XSLTransformation->loadXML($xslt);

        return \AutomaticImportTransform::TransformXml($XSLTransformation, $xmlDOMResponse);
    }
}
