<?php

namespace Blazemedia\Affiliation\Providers;

use Blazemedia\Affiliation\Utils\Logger;
use Blazemedia\Affiliation\Rendering\Disclaimer;
use Blazemedia\Affiliation\Support\Environment;
use Blazemedia\Affiliation\Rendering\RenderResponse;
use Blazemedia\Affiliation\Rendering\Parameters;
use Blazemedia\Affiliation\Rendering;

class FrontendServiceProvider implements Contract\ServiceProviderInterface
{
    use Trait\HasFormatsInjector, Trait\HasServerRequest,
        Trait\HandleZoneFormat,   Trait\LinkConverter,
        Trait\HasDebugInspector, Trait\HasPostMetaManager,
        Rendering\Trait\DebugPrint;

    protected \WP_Post $post;
    protected RenderResponse $renderResponse;
    private Disclaimer $disclaimer;

    public function __construct() 
    {
        $this->disclaimer = Disclaimer::getInstance();
        add_action('wp', [$this, 'register']);
    }


    public function register(): void
    {
        /// verifica se siamo nel fronted di una single post di uno dei post types configurati
        if (!is_singular( Environment::get('BLAZE_AFFILIATION_POST_TYPES') )) return;

        $post = get_post();

        if (!$post) return;

        $this->post = $post;

        // if( !$this->hasFormats( $this->post ) ) return;

        $this->renderResponse = $this->getRenderResponse();

        add_filter( 'the_content', [ $this, 'injectAffiliationInContent' ], 4, 1 );                
        add_action( 'wp_head',     [ $this, 'injectAffiliationStyles'    ], 20 );
        // Enqueue debug inspector for techteam only
        $this->enqueueDebugInspector($this->renderResponse);
    }

    public function injectAffiliationInContent( string $content ): string
    {
        $content = $this->inject($content, $this->renderResponse);

        if ($this->disclaimer->getStatus()) {
            $content = $this->disclaimer->printDisclaimer($content);
        }

        return $content;
    }


    public function injectAffiliationStyles(): void
    {
        $this->injectStyles( $this->renderResponse );
    }


    protected function getRenderResponse(): RenderResponse 
    {
        // Prepare post via action to centralize old shortcode and zone handling
        do_action('blz_affiliation_prepare_post', $this->post);
        $post = apply_filters('blz_affiliation_get_prepared_post', null, $this->post);
        if (!$post instanceof \WP_Post) {
            $post = $this->post;
        }

        // Compute current signature and compare with stored to decide cache usage
        $currentSignature = (new Parameters($post))->getSignature();
        $storedSignature  = $this->getMetaSignature($post);

        $this->getApiCallForDebug($post, $currentSignature);

        if ($currentSignature === $storedSignature) {
            $renderResponse = $this->getMetaRenderResponse($post);
            if (!$renderResponse->isEmpty()) {
                return $renderResponse;
            }
        } else {
            $this->deleteMetaRenderResponse($post);
        }

        $renderResponse = $this->getRemoteRenderResponse($post);

        if ($renderResponse->isEmpty()) {
            Logger::write('FrontendServiceProvider: Remote render response is empty, returning original content', 'ERROR');                                
        }
        
        return $renderResponse;
    }


    protected function getRemoteRenderResponse($post): RenderResponse
    {

        $renderResponse = $this->requestFormats($post);

        if ($renderResponse->isEmpty()) {

            Logger::write('FrontendServiceProvider: Requested formats are empty, returning empty render response', 'ERROR');

        } else {

            $this->setMetaRenderResponse($post, $renderResponse);
        }

        return $renderResponse;
    }

    
}
