using InABox.Core;
using InABox.Core.Postable;
using InABox.Scripting;
using System;
using System.Collections.Generic;
using System.Formats.Asn1;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace InABox.Poster.Timberline
{
    public class TimberlinePosterEngine<TPostable, TSettings> : PosterEngine<TPostable, ITimberlinePoster<TPostable, TSettings>, TSettings>
        where TPostable : Entity, IPostable, IRemotable, IPersistent, new()
        where TSettings : TimberlinePosterSettings<TPostable>, new()
    {

        private ScriptDocument? _script;
        private bool _hasCheckedScript;

        protected override ITimberlinePoster<TPostable, TSettings> CreatePoster()
        {
            var poster = base.CreatePoster();
            poster.Script = GetScriptDocument();
            return poster;
        }

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

            var settings = GetSettings();
            if (settings.ScriptEnabled && !string.IsNullOrWhiteSpace(settings.Script))
            {
                var document = new ScriptDocument(settings.Script);
                if (!document.Compile())
                {
                    throw new Exception("Script failed to compile!");
                }
                _script = document;
            }
            else
            {
                _script = null;
            }

            _hasCheckedScript = true;
            return _script;
        }

        public override bool BeforePost(IDataModel<TPostable> model)
        {
            return Poster.BeforePost(model);
        }

        protected override IPostResult<TPostable> DoProcess(IDataModel<TPostable> model)
        {
            return Poster.Process(model);
        }
        public override void AfterPost(IDataModel<TPostable> model, IPostResult<TPostable> result)
        {
            Poster.AfterPost(model, result);
        }
    }
}
