<?php
namespace SEE\WC\CreativeSearch\Presentation\Integration\Snippet;
use SEE\WC\CreativeSearch\Presentation\Utils\PluginUtils;
use Impresee\CreativeSearchBar\Domain\UseCases\GetImpreseeSnippetFilename;
use Impresee\CreativeSearchBar\Core\Constants\Services;

if (! defined('ABSPATH')){
    exit;
}

class ImpreseeSnippet {
    private $snippet_script_key;
    private $get_snippet_filename;
    private $utils;
    private $services;

    public function __construct(
        PluginUtils $utils,
        GetImpreseeSnippetFilename $get_snippet_filename,
        Services $services
    ) {
        $this->get_snippet_filename = $get_snippet_filename;
        $this->snippet_script_key = 'see-wccs-impresee-snippet';
        $this->utils = $utils;
        $this->services = $services;
    }

    private function getSnippetFilename(){
        $snippet_filename_local = get_option("see_wccs_impresee_snippet_filename", "");
        if ($snippet_filename_local != "") {
            return $snippet_filename_local;
        }

        $snippet_filename_promise = $this->get_snippet_filename->execute($this->utils->getStore());
        $snippet_filename_either = $snippet_filename_promise->wait();
        $snippet_filename = $snippet_filename_either->either(
            function ($failure) { 
                // todo check maybe
                error_log("An error has ocurred while obtaining the snippet filename: \n" . $failure);
                return "";
            },
            function ($filename) { 
                update_option("see_wccs_impresee_snippet_filename", $filename);    
                return $filename; 
            }
        );
        return $snippet_filename;
    }
    /**
    * Method in charge of generating the snippet, given all the configuration and connection to Impresee
    */
    public function generate_snippet(){

        $filename = $this->getSnippetFilename(); 
        $src = $filename;
        $key = $this->snippet_script_key;
        // write filename
        wp_register_script($key, $src, [] , '1.0', ['strategy' => 'async']);

        wp_enqueue_script($key);

        wp_add_inline_script($key, "");
        }

}
