using RothenburgAR.UI;
using UnityEngine;
using Vuforia;

namespace RothenburgAR.Exhibition
{
    class ImageExhibitBehaviour : ExhibitBehaviour
    {
        protected new void Start()
        {
            base.Start();
            CreateColoredOutline();
        }

        private void CreateColoredOutline()
        {
            var currentImageTargetBehaviour = Tracker as ImageTargetBehaviour;
            if (currentImageTargetBehaviour == null) return;
            
            var subGO = new GameObject("OutlineContainer");
            subGO.transform.parent = currentImageTargetBehaviour.gameObject.transform;
            subGO.transform.localScale = Vector3.one;

            var outlineRenderer = subGO.AddComponent<LineRenderer>();
            outlineRenderer.useWorldSpace = false;
            outlineRenderer.startWidth = 0.01f;
            outlineRenderer.endWidth = 0.01f;
            Vector2 size = currentImageTargetBehaviour.GetSize();
            size /= currentImageTargetBehaviour.gameObject.transform.localScale.z;

            //produces weird seam at begin/end point, so we'll loop it ourselves by drawing back to topLeft and topRight manually
            outlineRenderer.loop = false;

            Vector3 topLeft = new Vector3(-size.x / 2, 0, -size.y / 2);
            Vector3 topRight = new Vector3(size.x / 2, 0, -size.y / 2);
            Vector3 bottomLeft = new Vector3(-size.x / 2, 0, size.y / 2);
            Vector3 bottomRight = new Vector3(size.x / 2, 0, size.y / 2);
            outlineRenderer.positionCount = 6;
            outlineRenderer.SetPosition(0, topLeft);
            outlineRenderer.SetPosition(1, topRight);
            outlineRenderer.SetPosition(2, bottomRight);
            outlineRenderer.SetPosition(3, bottomLeft);
            outlineRenderer.SetPosition(4, topLeft);
            outlineRenderer.SetPosition(5, topRight);

            outlineRenderer.material = UIColorSchemeManager.Instance.GetUIMaterial(UIMaterial.ExhibitOutline);
        }
    }
}
