<?php

namespace FiloBlu\Refilo\Observer;

use FiloBlu\Refilo\Helper\Data;
use Magento\Framework\Event\Observer;
use Magento\Framework\Event\ObserverInterface;
use Magento\Store\Model\StoreManagerInterface;

class AfterBuildCanonicalUrlResultsFetch implements ObserverInterface
{
    /**
     * @var Data
     */
    protected $helper;
    /**
     * @var StoreManagerInterface
     */
    protected $storeManager;
    /**
     * @var array
     */
    protected $storeCodes = [];

    /**
     * @param Data $helper
     * @param StoreManagerInterface $storeManager
     */
    public function __construct(
        Data $helper,
        StoreManagerInterface $storeManager
    )
    {
        $this->helper = $helper;
        $this->storeManager = $storeManager;
        $this->getStoreCodes();
    }

    public function execute(Observer $observer)
    {
        if (!$this->helper->isCanonicalUrlObserverEnabled()) {
            return;
        }

        $canonicalUrlModifier = $observer->getEvent()->getCanonicalUrlModifier();
        $contentType = $observer->getEvent()->getContentType();

        if (!in_array($contentType, explode(',', $this->helper->getCanonicalUrlObserverContentTypes()))) {
            return;
        }

        $storeCode = $canonicalUrlModifier->getStoreCode();
        $path = $canonicalUrlModifier->getPath();
        $url = $canonicalUrlModifier->getUrl();


        $canonicalUrlModifier->setPath($this->cleanUrl($path, $storeCode, $url));
        $canonicalUrlModifier->setUrl($this->cleanUrl($url, $storeCode));

    }

    protected function cleanUrl($url, $storeCode, $fallBack = null)
    {
        if (empty($url)) {
            return $url;
        }

        // https://filoblu.atlassian.net/browse/ANTMRGEST-1517
        if (strpos($url, '://') !== false) {
            $parsed = parse_url($url);
            if (is_array($parsed) && isset($parsed['path'])) {
                $url = $parsed['path'];
            }
        }

        $path = trim($url, '/');
        $storePrefix = "{$storeCode}/";

        if (strpos($path, $storePrefix) === 0) {
             $url = substr($path, strlen($storePrefix));
        } else {
            $url = $path;
        }

        return $url;
    }

    public function getStoreCodes() {

        foreach ($this->storeManager->getStores() as $store) {
            $this->storeCodes[] = $store->getCode();
        }


    }
}
