<?php

namespace Comitium5\DesignerBundle\Controller\CKEditor;

use Comitium5\ApiClientBundle\Client\Services\AssetApiService;
use Comitium5\ApiClientBundle\ValueObject\IdentifiedValue;
use Comitium5\DesignerBundle\Factory\Asset\AssetFactory;
use Comitium5\DesignerBundle\Form\Type\Asset\SingleAssetType;
use Comitium5\DesignerBundle\Helper\CKEditor\CkAssetHelper;
use Comitium5\DesignerBundle\Model\Interfaces\Asset\AssetInterface;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;

/**
 * Class CkAssetController
 *
 * @author Carles Gómez <carles@bab-soft.com>
 * @package Comitium5\DesignerBundle\Controller\CKEditor
 */
class CkAssetController extends Controller
{
    /**
     * @param Request $request
     *
     * @return Response
     * @throws \Exception
     */
    public function renderAction(Request $request)
    {
        $type      = $request->query->get("type");
        $assetData = $request->query->get('asset', null);

        $form = $this->createForm(SingleAssetType::class, $assetData["id"] ? $assetData["id"] : null, [
            "asset_type" => $type,
            'data_class' => null,
        ]);

        return $this->render('Comitium5DesignerBundle:CkAsset:modal.html.twig', [
            "asset" => $assetData,
            "form"  => $form->createView(),
            "type"  => $type,
        ]);
    }

    /**
     * @param Request $request
     * @param $id
     *
     * @return JsonResponse
     * @throws \Exception
     */
    public function fetchAssetDataAction(Request $request, $id)
    {
        $assetApiService = new AssetApiService($this->get("designer.api"));

        $data = $assetApiService->find(new IdentifiedValue($id));

        $factory = new AssetFactory();

        $asset = $factory->create($data);

        $parentAsset = null;

        if (!empty($data["parent"]["id"])) {
            $parentAsset = $factory->create(
                $assetApiService->find(new IdentifiedValue($data["parent"]["id"]))
            );
        }

        $absoluteUrl = (bool) $request->get("absoluteUrl", false);

        $poster = "";

        if ($asset->getImageRelated() !== null) {
            $relatedImage = $assetApiService->find(new IdentifiedValue($asset->getImageRelated()["id"]));

            $poster = $relatedImage["url"];
        }

        $url = $absoluteUrl ? $asset->getUrl() : $asset->getPath();

        return new JsonResponse([
            "id"      => $asset->getId(),
            "url"     => $url,
            "embed"   => $asset->getEmbed(),
            "title"   => $parentAsset instanceof AssetInterface ? $parentAsset->getTitle() : $asset->getTitle(),
            "poster"  => $poster,
            "html"    => "",
            "width"   => $asset->getWidth(),
            "height"  => $asset->getHeight(),
            "editUrl" => CkAssetHelper::prepareEditUrl(
                $this->getParameter("cs_backend_url"),
                $request->getLocale(),
                $asset->getId(),
                $this->getUser()->getToken()
            ),
        ]);
    }

    /**
     * @param Request $request
     * @param $id
     *
     * @return Response
     * @throws \Exception
     */
    public function cropsTemplateAction(Request $request, $id)
    {
        $assetApiService = new AssetApiService($this->get("designer.api"));

        $data = $assetApiService->find(new IdentifiedValue($id));

        $factory = new AssetFactory();

        $asset = $factory->create($data);

        $absoluteUrl = (bool) $request->get("absoluteUrl", false);

        $resizeId = $request->query->get("resize", null);
        $cropData = [];

        foreach ($asset->getChildren() as $child) {
            $imageMetaData = $child["metadata"];
            $crop = $imageMetaData["crop"];
            $childEntity = $factory->create($assetApiService->find(new IdentifiedValue($child["id"])));

            if (!empty($crop)) {
                $key  = $crop["id"];

                $cropData[$key]['crop'] = [
                    "id"   => $crop["id"],
                    "name" => $crop["name"],
                ];

                $url = $absoluteUrl ?
                    $childEntity->getUrl():
                    $childEntity->getPath();

                $cropData[$key]['assets'][] = [
                    "resize" => $imageMetaData["imageResize"],
                    "width" => $childEntity->getWidth(),
                    "height" => $childEntity->getHeight(),
                    "id" => $childEntity->getId(),
                    "src" => $url,
                ];
            }

        }

        return $this->render('Comitium5DesignerBundle:CkAsset:crops-modal.html.twig', [
            "cropsData"   => $cropData,
            "resizeId"    => $resizeId,
            "original"    =>  [
                "src" => $absoluteUrl ? $asset->getUrl() : $asset->getPath(),
                "width"  => $asset->getWidth(),
                "height" => $asset->getHeight(),
            ]
        ]);
    }

    /**
     * @param AssetInterface $asset
     *
     * @return string|string[]|null
     */
    private function getAssetCKEditorHtml(AssetInterface $asset)
    {
        $type = $asset->getType();

        $html = $this
            ->get("cs.manager.config_parameter")
            ->getParamValues(ConfigParameterKey::ASSET_CK_EDITOR_HTML, $type);

        if (empty($html)) {
            return null;
        }

        $title = $asset->getDefaultLang()->getTitle();
        $description = $asset->getDefaultLang()->getDescription();
        $author = $asset->getAuthor();

        $html = str_replace("@asset-type@", $type, $html);
        $html = str_replace("@asset-title@", $title, $html);
        $html = str_replace("@asset-desc@", $description, $html);
        $html = str_replace("@asset-author@",  empty($author) ? "" : $author, $html);

        return $html;
    }
}
