using InABox.Core;
using InABox.Scripting;

namespace InABox.Poster.Shared;

public abstract class BasePosterEngine<TPostable, TPoster, TSettings> : PosterEngine<TPostable, TPoster, TSettings>
    where TPostable : Entity, IPostable, IRemotable, IPersistent, new()
    where TPoster : class, IPoster<TPostable, TSettings>
    where TSettings : PosterSettings, new()
{
    private ScriptDocument? _script;
    private bool _hasCheckedScript;

    protected ScriptDocument? GetScriptDocument()
    {
        if (_hasCheckedScript)
        {
            return _script;
        }

        var settings = GetSettings();
        _script = GetScriptDocument(settings);

        _hasCheckedScript = true;
        return _script;
    }

    public static ScriptDocument? GetScriptDocument(TSettings settings)
    {
        if (settings.ScriptEnabled && !string.IsNullOrWhiteSpace(settings.Script))
        {
            var document = new ScriptDocument(settings.Script);
            if (!document.Compile())
            {
                throw new Exception("Script failed to compile!");
            }
            return document;
        }
        else
        {
            return null;
        }
    }
}
