<?php
/**
 * 2018 Paysera
 *
 * NOTICE OF LICENSE
 *
 * This source file is subject to the Academic Free License (AFL 3.0)
 * that is bundled with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://opensource.org/licenses/afl-3.0.php
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@prestashop.com so we can send you a copy immediately.
 *
 * @author Paysera <plugins@paysera.com>
 * @copyright 2018 Paysera
 * @license http://opensource.org/licenses/afl-3.0.php Academic Free License (AFL 3.0)
 *  International Registered Trademark & Property of Paysera
 */
namespace Paysera\Service\Renderer;

if (!defined('_PS_VERSION_')) {
    exit;
}

use Paysera\Form\AdminFormInterface;

class FormRenderer
{
    /**
     * @var AdminFormInterface
     */
    private $form;
    /**
     * @var string
     */
    private $table;
    /**
     * @var string
     */
    private $identifier;
    /**
     * @var callable
     */
    private $setSelectedTab;

    /**
     * @param AdminFormInterface $form
     * @param string $table
     * @param string $identifier
     * @param callable $setSelectedTab
     */
    public function __construct(AdminFormInterface $form, $table, $identifier, callable $setSelectedTab)
    {
        $this->form = $form;
        $this->table = $table;
        $this->identifier = $identifier;
        $this->setSelectedTab = $setSelectedTab;
    }

    /**
     * @return string
     */
    public function render()
    {
        if (\Tools::isSubmit($this->form->getSubmitActionName())) {
            $output = $this->form->validate();

            if ($output->isSuccess()) {
                $output = $this->form->update();
            }

            $context = \Context::getContext();
            $context->cookie->payseraMessageSuccess = $output->isSuccess();
            $context->cookie->payseraConfigMessage = $output->getMessage();

            call_user_func($this->setSelectedTab, $this->form->getFormId());
        }

        return $this->form->getFormHelper()->generateFormOutput(
            $this->form,
            $this->table,
            $this->identifier
        )
        . $this->form->additionalHTML();
    }
}
