using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;

# if UNITY_EDITOR
using UnityEditor;
#endif

[RequireComponent(typeof(Rigidbody2D), typeof(BoxCollider2D))]
public class SceneWarper : MonoBehaviour
{
    // Scriptable object is to have a unique identification of a location.

    [SerializeField]
    private WarpLocation location;

    [SerializeField]
    private WarpLocation target;

    [SerializeField]
    private WarpEvent warpRequest;

    [SerializeField]
    private GameObject spawnLocation;

    public Vector2 SpawnLocation { get { return spawnLocation.transform.position; } }

    public WarpLocation Location { get { return location; } }

    public WarpLocation Target { get { return target; } }

#if UNITY_EDITOR

    private void OnValidate()
    {
        location?.Set(this);

        if (spawnLocation == null)
        {
            spawnLocation = new GameObject();
            spawnLocation.name = "Spawn Location";
            spawnLocation.transform.SetParent(this.transform);
        }
        else
        {
            if (spawnLocation.transform.position.z != 0)
            {
                Vector3 newPosition = spawnLocation.transform.position;
                newPosition.z = 0;
                spawnLocation.transform.position = newPosition;
            }
        }
    }

    public void OnDrawGizmos()
    {
        if (spawnLocation == null)
        {
            spawnLocation = new GameObject();
            spawnLocation.name = "Spawn Location";
            spawnLocation.transform.SetParent(this.transform);
            spawnLocation.transform.localPosition = Vector3.zero;
        }

        Bounds getBounds = GetComponent<BoxCollider2D>().bounds;
        getBounds.Expand(0.05f);

        if (getBounds.Contains(spawnLocation.transform.position))
        {
            Gizmos.color = Color.red;
        }
        else
        {
            Gizmos.color = Color.green;
        }


        Gizmos.DrawWireSphere(spawnLocation.transform.position, 0.05f);
    }

#endif

    private void OnTriggerEnter2D(Collider2D collision)
    {
        if (collision.CompareTag("Player"))
        {
            warpRequest.Invoke(target);
        }
    }
}

#if UNITY_EDITOR


[CustomEditor(typeof(SceneWarper))]
public class SceneWarperInspector : Editor
{
    public override void OnInspectorGUI()
    {
        base.OnInspectorGUI();

        if (GUILayout.Button("Go to target location"))
        {
            ((SceneWarper)target).Target.GoToLocation();
        }
    }
}

#endif