<?php

namespace RTMCustomMails\Renderer;

use RTMCustomMails\ContextBuilder\WPContextBuilder;
use RTMCustomMails\Email\RTMCustomEmail;
use RTMMailComposer\Model\CustomMail;
use RTMMailComposer\Model\EmailSection;
use RTMMailComposer\Renderer\TwigEmailRenderer;
use Timber\Loader;
use Timber\Timber;
use WordpressModels\Traits\SingletonTrait;

class TimberEmailRenderer extends TwigEmailRenderer
{

    use SingletonTrait;

    protected function __construct()
    {
        $contextBuilder = new WPContextBuilder();
        parent::__construct($contextBuilder->getRegistry(), (new Loader())->get_twig());

        add_action('wrce_email_sections', [$this, 'render'], 10, 2);

        add_action('wrce_render_email_section', [$this, 'renderSection'], 10, 3);

        do_action('wrce_register_context_builders', $contextBuilder->getRegistry());
    }

    public function filterTimberContext(array $context)
    {
        if (!doing_action('wrce_email_sections')) {
            return $context;
        }

        // unset internal timber context
        foreach (['http_host', 'wp_title', 'body_class', 'request', 'user', 'theme', 'posts', 'wp_head', 'wp_footer'] as $key) {
            unset($context[$key]);
        }

        return $context;
    }

    public function render(CustomMail $mail, object $mailObject, array $initialContext = []): string
    {
        $currentContext = Timber::$context_cache;
        add_filter('timber/context', [$this, 'filterTimberContext']);

        $context = Timber::context() + $initialContext;
        $render = parent::render($mail, $mailObject, $context);

        // reset timber context
        Timber::$context_cache = $currentContext;
        remove_filter('timber/context', [$this, 'filterTimberContext']);

        if ($mail instanceof RTMCustomEmail) {
            $render = $mail->style_inline($render);
        }

        return $render;
    }

    /**
     * @inheritDoc
     */
    public function renderSection(EmailSection $section, array $context): string
    {
        [$action, $action_arguments] = apply_filters('wrce_email_section_action', $section->getId(), $context);

        // set default args for default hook
        if ($action === 'wrce_render_email_section') {
            $renderedSection = parent::renderSection($section, $context);
        } else {
            // used for custom hooks, like woocoomerce_email_order_details
            ob_start();
            do_action($action, ...$action_arguments);
            $renderedSection = ob_get_clean();
            ob_flush();
        }
        return $renderedSection;
    }
}
