<?php

namespace Comitium5\DesignerBundle\Form\Resolver;

use Comitium5\DesignerBundle\Provider\SubsiteProvider;
use Symfony\Component\Filesystem\Filesystem;

/**
 * Class CkEditorResolver
 *
 * @author Carles Gómez <carles@bab-soft.com>
 * @package Comitium5\DesignerBundle\Form\Resolver
 */
class CkEditorResolver
{
    const DEFAULT_SKIN = "kama";
    const CUSTOM_CKEDITOR_FILENAME = "ckeditor-custom.css";

    /**
     * @var array
     */
    private $config;

    /**
     * @var string
     */
    private $webPath;

    /**
     * @var
     */
    private $subsiteProvider;

    /**
     * CkEditorResolver constructor.
     *
     * @param array $config
     * @param $webPath
     * @param SubsiteProvider $subsiteProvider
     */
    public function __construct(
        array $config,
        $webPath,
        SubsiteProvider $subsiteProvider
    )
    {
        $this->config  = $config;
        $this->webPath = realpath($webPath);
        $this->subsiteProvider = $subsiteProvider;
    }

    /**
     * @return array
     */
    public static function getExtensionParameters()
    {
        return [
            'template',
            'toolbar',
            'style',
            'config'
        ];
    }


    /**
     * @param $requestConfig
     * @return array
     * @throws \Exception
     */
    public function resolve($requestConfig)
    {
        $requestConfig = $this->buildDefaults($requestConfig);

        $config = [
            "plugins" => $this->config['plugins'],
            "config"  => [],
        ];

        foreach (self::getExtensionParameters() as $parameter) {
            if(!array_key_exists($requestConfig["$parameter"], $this->config["{$parameter}s"])) {
                throw new \Exception(sprintf("$parameter %s is not defined", $requestConfig[$parameter]));
            }
        }

        $config['config'] = $this->resolveConfig($requestConfig);

        return $config;
    }

    /**
     * @param $parameters
     * @return array
     */
    private function buildDefaults($parameters)
    {
        $defaults = [
            'template' => $this->config['default_template'],
            'style'    => $this->config['default_style'],
            'toolbar'  => $this->config['default_toolbar'],
            'config'   => $this->config['default_config'],
            'skin'     => self::DEFAULT_SKIN,
        ];

        return array_merge($defaults, $parameters);
    }

    /**
     * @param array $options
     * @return array
     * @throws \Doctrine\ORM\ORMException
     * @throws \Exception
     */
    private function resolveConfig(array $options)
    {
        $defaults = array(
            'toolbar'  => $options['toolbar'],
            'style'    => $options['style'],
            'template' => $options['template'],
            'skin'     => $options['skin'],
        );

        $config = array_merge($this->config['configs'][$options['config']], $defaults);

        $customFile = $this->getCustomCssBySubSite();

        if (!empty($customFile)) {
            $config["contentsCss"] = array_merge($config["contentsCss"], array($customFile));
        }

        return $config;

    }

    /**
     * @return string|string[]|null
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function getCustomCssBySubSite()
    {
        $acronym = $this
            ->subsiteProvider
            ->getSubSite()
            ->getAcronym();

        $fileSystem = new Filesystem();

        $filePath = $this->webPath.DIRECTORY_SEPARATOR."uploads".DIRECTORY_SEPARATOR."static".DIRECTORY_SEPARATOR.$acronym.DIRECTORY_SEPARATOR.self::CUSTOM_CKEDITOR_FILENAME;

        if ($fileSystem->exists($filePath)) {
            return str_replace($this->webPath, "",$filePath);
        }

        return null;
    }
}
