<?php

use CCDN\Helpers\Api\ApiHandler;
use CCDN\Helpers\Caching\Cache;
use CCDN\Helpers\CCDNFunctions;
use CCDN\Helpers\DB\SettingsSave;
use CCDN\Helpers\SecondIn;
use CCDN\Helpers\Settings;
use GuzzleHttp\Client;

require_once ENGINE_DIR . '/inc/CCDN/vendor/autoload.php';

class CCDN
{
    private $settings = null;
    private $cache = null;

    public function __construct()
    {
        $this->settings = Settings::all();
        $this->cache = new Cache();

        $this->getActualDomains();
    }

    /**
     * @param dle_template $tpl
     */
    public function preCompile($tpl)
    {
        if ($this->settings->domain_embed !== null) {
            if (($xfvalue = $this->getXFValueTag($tpl->data, 'embed_field')) !== false) {
                $tpl->data[$xfvalue] = $this->replaceDomainInUrl($tpl->data[$xfvalue], $this->settings->domain_embed);
            }

            if (($xfvalue = $this->getXFValueTag($tpl->data, 'trailer_field')) !== false) {
                $tpl->data[$xfvalue] = $this->replaceDomainInUrl($tpl->data[$xfvalue], $this->settings->domain_embed);
            }
        }

        if ($this->settings->domain_image !== null) {
            $xfvalue_new_franchise_poster = $this->getXFValueTag($tpl->data, 'new_franchise_poster');
            if ($xfvalue_new_franchise_poster !== false) {
                $tpl->data[$xfvalue_new_franchise_poster] = $this->replaceDomainInUrl($tpl->data[$xfvalue_new_franchise_poster], $this->settings->domain_image);
            }

            $xfvalue_button_poster = $this->getXFValueTag($tpl->data, 'button_poster');
            if ($xfvalue_button_poster !== $xfvalue_new_franchise_poster) {
                if ($xfvalue_button_poster !== false) {
                    $tpl->data[$xfvalue_button_poster] = $this->replaceDomainInUrl($tpl->data[$xfvalue_button_poster], $this->settings->domain_image);
                }
            }
        }
    }

    /**
     * @param $tpl_data
     * @param $xfkey
     * @return false|string
     */
    private function getXFValueTag($tpl_data, $xfkey)
    {
        if ($this->settings->$xfkey === null)
            return false;

        $xfvalue_tag = "[xfvalue_{$this->settings->$xfkey}]";

        if (!array_key_exists($xfvalue_tag, $tpl_data))
            return false;

        return $xfvalue_tag;
    }

    /**
     * @param $url
     * @param $domain
     * @return string|string[]|null
     */
    public function replaceDomainInUrl($url, $domain)
    {
        if ($domain === null)
            return $url;

        return preg_replace('/^(https?:)?\/\/[^\/]+/', $domain, $url, 1);
    }

    private function getActualDomains()
    {
        if ($this->cache->has(__METHOD__))
            return;

        try {
            $response = (new ApiHandler(2, false, SecondIn::minute(10)))->getDomains()->getBody();
        } catch (Exception $e) {
            $response = null;
        }

        if (!isset($response['embed']) || !isset($response['image'])) {
            $this->cache->set(__METHOD__, '', SecondIn::minute(11));
            return;
        }

        if (CCDNFunctions::removeSchema($response['embed']) !== $this->settings->domain_embed
            || CCDNFunctions::removeSchema($response['image']) !== $this->settings->domain_image) {
            $configSave = new SettingsSave([
                'domain_embed' => CCDNFunctions::removeSchema($response['embed']),
                'domain_image' => CCDNFunctions::removeSchema($response['image']),
            ]);
            $configSave->saveAll();
            clear_cache(['news_', 'related_', 'tagscloud_', 'archives_', 'calendar_', 'topnews_', 'informer_', 'rss', 'stats']);
        }

        $this->cache->set(__METHOD__, '', SecondIn::minute(30));
    }

    public function getActualizeJS()
    {
        // support old chained
        return '';
    }

}