<?php

namespace FiloBlu\Refilo\Plugins;

use Magento\Cms\Model\Page\DataProvider;
use Magento\Framework\UrlInterface;
use Magento\Store\Model\StoreManagerInterface;

class PageDataProvider
{
    /**
     * @var StoreManagerInterface
     */
    protected $storeManager;

    public function __construct(
        StoreManagerInterface $storeManager
    ) {
        $this->storeManager = $storeManager;
    }

    /**
     * TODO: use  modifier pools instead
     * @param DataProvider $subject
     * @param $result
     * @return mixed
     * @throws \Magento\Framework\Exception\NoSuchEntityException
     */
    public function afterGetData(DataProvider $subject, $result)
    {
        if(!is_array($result))
        {
            return $result;
        }

        //@ToDo remove reference to $page
        foreach ($result as &$page) {
            if (!isset($page['og_data_image']) || empty($page['og_data_image'])) {
                continue;
            }
            $path = $page['og_data_image'];
            $imageInfo = pathinfo($path);
            $page['og_data_image'] = [0 => [
                'url' => $this->storeManager->getStore()->getBaseUrl(UrlInterface::URL_TYPE_MEDIA) . $path,
                'name' => $imageInfo['basename'],
                'size' => 0,
                'type' => 'image/' . $imageInfo['extension']
            ]
            ];
        }
        return $result;
    }
}
