<?php

/**
 * Custom extension for Isotope for Contao
 *
 * Copyright (c) 2014 Benjamin Roth [http://www.esales-media.de]
 *
 * @package eSM_isotope_custom
 * @link    http://www.esales-media.de
 * @license commercial
 */

namespace eSM_isotope_custom;

use Haste\Input\Input;
use Isotope\Model\Product;
use Isotope\Interfaces\IsotopeAttribute;

class InsertTag extends \Controller
{
    public function eSMReplaceInsertTags($strTag)
    {
        $elements = explode('::', $strTag);
        if ($elements[0] == 'iso_custom_product')
        {
            $fragments = explode(':', $elements[1]);

            if ($fragments[0] && ($objProduct = $this->findCurrentProduct($fragments[1])) !== null)
            {
                $objAttribute = $GLOBALS['TL_DCA']['tl_iso_product']['attributes'][$fragments[0]];

                if (!($objAttribute instanceof IsotopeAttribute)) {
                    throw new \InvalidArgumentException($fragments[0] . ' is not a valid attribute');
                }

                return $objAttribute->generate($objProduct, array());
            }
        }

        return false;
    }

    private function findCurrentProduct($id = null)
    {
        if (null !== $id) {
            return Product::findPublishedByPk($id);
        } elseif (Product::getActive() !== null) {
            return Product::getActive();
        } else {
            return Product::findAvailableByIdOrAlias(Input::getAutoItem('product', false, true));
        }
    }
}