<?php

namespace KupShop\KupShopBundle\Util\System;

use KupShop\KupShopBundle\Context\DomainContext;
use KupShop\KupShopBundle\Util\StringUtil;

class UrlFinder
{
    /** @var DomainContext */
    protected $domainContext;

    protected string $cdnPrefix;

    public function shopUrl($file)
    {
        return '/'.ltrim($file, '/');
    }

    public function shopUrlAbsolute($file)
    {
        if (StringUtil::isAbsoluteUrl($file)) {
            return $file;
        }

        return 'https://'.$this->domainContext->getActiveId().'/'.ltrim($file, '/');
    }

    public function staticUrl($file)
    {
        if (StringUtil::isAbsoluteUrl($file)) {
            return $file;
        }

        return $this->getCdnPrefix().'/'.ltrim($file, '/');
    }

    public function staticUrlAbsolute($file)
    {
        if (StringUtil::isAbsoluteUrl($file)) {
            return $file;
        }

        if (!$this->hasCDN()) {
            return $this->shopUrlAbsolute($file);
        }

        return $this->getCdnPrefix().'/'.ltrim($file, '/');
    }

    public function hasCDN()
    {
        return $this->getCdnPrefix() !== '';
    }

    /**
     * @required
     */
    public function setDomainContext(DomainContext $domainContext): void
    {
        $this->domainContext = $domainContext;
    }

    public function getCdnPrefix()
    {
        if (!isset($this->cdnPrefix)) {
            $cdn = \Settings::getDefault()->cdn ?? [];
            $this->cdnPrefix = (($cdn['active'] ?? 'N') == 'Y' && findModule(\Modules::CDN)) ? $cdn['url'] : '';
        }

        return $this->cdnPrefix;
    }

    public function setCdnPrefix(string $cdnPrefix): void
    {
        $this->cdnPrefix = $cdnPrefix;
    }
}
