using UnityEngine;
using System;
using System.Collections.Generic;
using mgaia.Utils;

namespace mgaia.tk2d
{
    /// <summary>
    /// Behaviour utilizado para setar o tamanho do texto automaticamente para encaixar uma área
    /// </summary>
    /// <owner>Victor</owner>
    public class ReescalableTextMesh : MonoBehaviour
    {
        private tk2dTextMesh mTextMesh;
        private string mReferencialText;
        private float mReferencialScale;
        private Bounds mReferencialBounds;

        public ReescaleMode Mode = ReescaleMode.DontEnlarge;

        public enum ReescaleMode
        {
            DontEnlarge,
            Fill
        }

        private void Awake()
        {
            mTextMesh = GetComponent<tk2dTextMesh>();

            Assert.AssertTrue(mTextMesh != null, "Não foi possível encontrar o tk2dTextMesh!");

            CalculateReferencial();
        }

        /// <summary>
        /// Calcula o tamanho referencial de modo que o texto atual seja o molde
        /// </summary>
        public void CalculateReferencial()
        {
            mReferencialText = mTextMesh.text;
            mReferencialScale = mTextMesh.scale.x;
            mReferencialBounds = mTextMesh.GetEstimatedMeshBoundsForString(mTextMesh.text);
        }

        /// <summary>
        /// Seta o texto e seta o novo tamanho para encaixar
        /// </summary>
        public void SetTextAndReescale(string text)
        {
            mTextMesh.text = text;

            float scale = mReferencialScale * (mReferencialText.Length / (text.Length * 1.0f));

            mTextMesh.scale = new Vector3(scale, scale, scale);
            mTextMesh.Commit();

            Bounds newTextBounds = mTextMesh.GetEstimatedMeshBoundsForString(text);

            float xFactor = mReferencialBounds.extents.x / newTextBounds.extents.x;
            float newScaleComponent = scale * xFactor;

            if (Mode == ReescaleMode.DontEnlarge)
            {
                newScaleComponent = Mathf.Min(newScaleComponent, mReferencialScale);
            }

            mTextMesh.scale = new Vector3(newScaleComponent, newScaleComponent, newScaleComponent);
        }
    }
}