/*
<copyright file="BGDBUiElementBinderTemplate.cs" company="BansheeGz">
    Copyright (c) 2018-2021 All Rights Reserved
</copyright>
*/

using System;
using UnityEngine;
using UnityEngine.UIElements;

namespace BansheeGz.BGDatabase
{
    [Serializable]
    public class BGDBUiElementBinderTemplate : BGDBUiElementBinderA
    {
        private static readonly BGDBTextProcessor TextProcessor = new BGDBTextProcessor();

        [SerializeField] private string template;

        private BGDBTextBinderRoot binder;

        public string Template
        {
            get => template;
            set
            {
                if(template==value) return;
                template = value;
                binder = null;
            }
        }
        public override string Title => "Template";

        public BGDBTextBinderRoot Binder => binder;


        public override object Value
        {
            get
            {
                if (binder == null || !string.Equals(binder.Template, template))
                {
                    binder = TextProcessor.Process(template);
                }

                if (binder.Error != null) throw new Exception("Template parsing error:" + binder.Error);
                
                var result = binder.Bind();
                if (binder.Error != null) throw new Exception("Template parsing error:" + binder.Error);
                return result;
            }
        }

        public override Type ValueType => typeof(string);

        public override void ReverseBind(UIDocument doc)
        {
            //not supported (not possible to implement)
        }
    }
}