using KitsuneCafe.SOAP;
using R3;
using UnityEngine;

namespace KitsuneCafe.Interaction
{
    public class SelectedObjectHandler : MonoBehaviour
    {
        [SerializeField]
        private GameObjectValue selectedObject;

        [Header("Default Outline")]
        [SerializeField]
        private Color color = Color.orangeRed;

        [SerializeField]
        private float width = 1f;

        [SerializeField]
        private Outline.Mode mode = Outline.Mode.OutlineAll;

        private void Awake()
        {
            selectedObject
                .AsObservable()
                .Scan<GameObject, GameObject>(null, SwapObjects)
                .Subscribe()
                .AddTo(this);
        }

        private GameObject SwapObjects(GameObject previous, GameObject current)
        {

            if (previous != null)
            {
                DeselectObject(previous);
            }

            if (current != null)
            {
                SelectObject(current);
            }

            return current;
        }

        private void DeselectObject(GameObject gameObject)
        {
            if (gameObject.TryGetComponent(out Outline outline))
            {
                outline.enabled = false;
            }
        }

        private Outline AddSelectionEffect(GameObject gameObject)
        {
            var outline = gameObject.AddComponent<Outline>();
            outline.OutlineColor = color;
            outline.OutlineWidth = width;
            outline.OutlineMode = mode;
            return outline;
        }

        private void SelectObject(GameObject gameObject)
        {
            if (!gameObject.TryGetComponent(out Outline outline))
            {
                outline = AddSelectionEffect(gameObject);
            }

            outline.enabled = true;
        }
    }
}
