<?php
/**
 * Webkul Software.
 *
 * @category Webkul
 *
 * @author    Webkul
 * @copyright Copyright (c) Webkul Software Private Limited (https://webkul.com)
 * @license   https://store.webkul.com/license.html
 */

namespace Webkul\AdvanceSeoManager\Model\RichSnippet\Context;

class Cms extends AbstractContext
{

    public function __construct(
        \Webkul\AdvanceSeoManager\Helper\JsonLd $jsonLdHelper,
        \Magento\Framework\Json\Helper\Data $jsonHelper,
        \Webkul\AdvanceSeoManager\Model\RichSnippet\Context\Cms\DataPoolInterface $cmsDataPool
    ) {
        $this->jsonLdHelper = $jsonLdHelper;
        $this->jsonHelper = $jsonHelper;
        $this->cmsDataPool = $cmsDataPool;
    }

    /**
     * {@inheritdoc}
     */
    public function build($contextData)
    {
        $jsonLdData = $this->createJsonLdFormatArray($contextData);
        $jsonLdString = '';
        $standAloneJsonLd = [];
        if (isset($jsonLdData["standAlone"])) {
            $standAloneJsonLd = $jsonLdData["standAlone"];
            unset($jsonLdData["standAlone"]);
        }

        if (count($jsonLdData) > 0) {
            $jsonLdData['@context'] = "http://schema.org";
            $jsonLdString .= $this->getJsonLdFormat($this->jsonHelper->jsonEncode($jsonLdData));
        }

        if (count($standAloneJsonLd) > 0) {
            foreach ($standAloneJsonLd as $saj) {
                $saj['@context'] = "http://schema.org";
                $jsonLdString .= $this->getJsonLdFormat($this->jsonHelper->jsonEncode($saj));
            }
        }
        return $jsonLdString;
    }

    /**
     * {@inheritdoc}
     */
    public function createJsonLdFormatArray($contextData)
    {
        $richSnippetFormat = $this->jsonLdHelper->getCmsRichSnippetData();
        $data = [];
        if ($contextData && $contextData->getId()) {
            $data = $this->getRichCmsSnippet($contextData, $richSnippetFormat);
            return $data;
        }
        return [];
    }

    /**
     * get cms page rich snippet
     *
     * @param  \Magento\Cms\model\Page $contextData
     * @param  array $richSnippetFormat
     * @return array
     */
    public function getRichCmsSnippet($contextData, $richSnippetFormat)
    {
        try {
            $result = [];
            if (count($richSnippetFormat) > 0) {
                foreach ($richSnippetFormat as $providerCode => $status) {
                    if ($status) {
                        // @TODO implement exceptions catching
                        $result = array_replace_recursive(
                            $result,
                            $this->cmsDataPool->get($providerCode)->getData($contextData)
                        );
                    }
                }
            }
            return $result;
        } catch (\Exception $e) {
            // @TODO log errors
            return [];
        }
    }
}
