﻿using System.Collections.Generic;
using Febucci.TextAnimatorForUnity;
using Febucci.TextAnimatorForUnity.Effects.Core;
using UnityEngine;

namespace Utage
{
    //宴のTextMeshPro対応をさらにカスタムしてTextAnimatorに対応する
	[AddComponentMenu("Utage/TextAnimator/UtageForTextAnimator")]
	public class UtageForTextAnimator : MonoBehaviour
        , ICustomTextParser
    {
        [SerializeField] AnimationsDatabase animationsDatabase;
        [SerializeField] List<EffectScriptableBase> newEffects = new ();
        [SerializeField] List<string> newEventsTags = new ();

        void Awake()
        {
            SetCustomTextParser();
        }

        void OnDestroy()
        {
            ClearCustomTextParser();
        }

        public void SetCustomTextParser()
        {
            //新しいエフェクトタグを登録
			TextParserForTextAnimator.NewBehaviorTags.Clear();
            TextParserForTextAnimator.NewAppearancesTags.Clear();
            
            foreach (var keyValuePair in animationsDatabase.Database)
            {
                AddEffect(keyValuePair.Value);
            }
            foreach (var effect in newEffects)
            {
                if(effect==null) continue;
                AddEffect(effect);
            }
            //新しいイベントタグを登録
            TextParserForTextAnimator.NewEventsTags.Clear();
            TextParserForTextAnimator.NewEventsTags.AddRange(newEventsTags);
			
            //テキスト解析処理をカスタム
            TextData.CreateCustomTextParser = CreateCustomTextParser;
            //ログテキスト作成をカスタム
            TextData.MakeCustomLogText = MakeCustomLogText;
            
            return;
        }
        
        public void AddEffect(Febucci.TextAnimatorCore.IEffect effect)
        {
            var tagId = effect.TagID;
            if (!TextParserForTextAnimator.NewBehaviorTags.Contains(tagId))
            {
                TextParserForTextAnimator.NewBehaviorTags.Add(tagId);
            }
            if (!TextParserForTextAnimator.NewAppearancesTags.Contains(tagId))
            {
                TextParserForTextAnimator.NewAppearancesTags.Add(tagId);
            }
        }
        
        public void ClearCustomTextParser()
        {
            TextData.CreateCustomTextParser = null;
            TextData.MakeCustomLogText = null;
        }

        //テキスト解析をカスタム
        TextParser CreateCustomTextParser(string text)
        {
			return new TextParserForTextAnimator(text);
        }

        //ログテキスト作成をカスタム
        string MakeCustomLogText(string text)
        {
			return new TextParserForTextAnimator(text,true).NoneMetaString;
        }
    }
}
