using System;
using Intrepid.Core.Camera;
using Intrepid.Core.Messages.Events;
using Intrepid.SimpleEvents;
using Intrepid.Utilities;
using UnityEngine;
using UnityEngine.UI;

namespace Intrepid.Core.UI
{
    [RequireComponent(typeof(RectTransform))]
    public class FlexibleWorkableAreaUI : EventListener
    {
        [GroupConfigurations, SerializeField] private float horizontalShift = 200f;

        private RectTransform RectTransform { get; set; }
        private CanvasScaler CanvasScaler { get; set; }
        protected override void InitializeVariables()
        {
            RectTransform = GetComponent<RectTransform>();
            CanvasScaler = GetComponentInParent<CanvasScaler>();
        }

        protected override void OnBootstrap()
        {
        }

        protected override void Subscriptions()
        {
            Subscribe<FlexibleWorkableAreaPaddingEvent>(e =>
            {
                if (!string.Equals(SubscriptionId, e.Id, StringComparison.CurrentCultureIgnoreCase)) return;
                var viewport = CameraSystem.Instance.MainCamera.WorldToViewportPoint(CameraSystem.Instance.CameraTargetPosition);
                var targetScreenPosition = new Vector2(CanvasScaler.referenceResolution.x * viewport.x, CanvasScaler.referenceResolution.y * viewport.y);
                if (targetScreenPosition.x > CanvasScaler.referenceResolution.x * .5f)
                {
                    var ap = RectTransform.anchoredPosition;
                    ap.x = -horizontalShift;
                    RectTransform.anchoredPosition = ap;
                }
                else
                {
                    var ap = RectTransform.anchoredPosition;
                    ap.x = horizontalShift;
                    RectTransform.anchoredPosition = ap;
                }
            });
        }
    }
}