using System;
using Unity.VisualScripting;
using UnityEngine;

[ExecuteAlways]
public class Connection : MonoBehaviour
{    public enum BuildState { EMPTY, DECONSTRUCTING, CONSTRUCTING, BUILT };

    public Node nodeA, nodeB;
    public bool allowed = true;
    public BuildState state = BuildState.EMPTY;
    public bool hovered = false;
    public LineRenderer lineRenderer;

    public void SetConnect()
    {
        if (!allowed) return;
        nodeA.connected.Add(nodeB);
        nodeB.connected.Add(nodeA);
    }

    public void DelConnect()
    {
        nodeA.connected.Remove(nodeB);
        nodeB.connected.Remove(nodeA);
    }

    private void Update()
    {
        // On Click
        if (Input.GetMouseButtonDown(0) && hovered && allowed) 
        {
            int player = GameManager.Instance.currentPlayer;

            if (state == BuildState.BUILT && nodeA.Owner == player && nodeB.Owner == player)
            {
                bool explode = Input.GetKey(KeyCode.LeftShift);
                var action = new GameManager.Action { nodeToId = nodeA.id, nodeFromId = nodeB.id, player = player, type = explode ? GameManager.ActionType.EXPLODE_CON : GameManager.ActionType.DESTRUCT_CON };
                GameManager.Instance.ExecuteAction(action);
            }
            else if(state == BuildState.EMPTY && (nodeA.Owner == player || nodeB.Owner == player))
            {
                var action = new GameManager.Action { nodeToId = nodeA.id, nodeFromId = nodeB.id, player = player, type = GameManager.ActionType.MOVE_UNITS };
                GameManager.Instance.ExecuteAction(action);
            }
        }


        if (Application.isPlaying && !allowed)        
            lineRenderer.enabled = false;
        else
        {
            float width = (hovered ? 0.6f : 0.3f) * (allowed ? state != BuildState.BUILT ? 0.6f : 1f : 0.1f);

            Color unbuiltColor = !allowed || state == BuildState.EMPTY ? new Color(0.2f, 0.2f, 0.2f) : new Color(0.8f, 0.8f, 0f);

            lineRenderer.startColor = allowed && state == BuildState.BUILT ? nodeA.transform.GetChild(0).GetComponent<Renderer>().sharedMaterial.color : unbuiltColor;
            lineRenderer.endColor = allowed && state == BuildState.BUILT ? nodeB.transform.GetChild(0).GetComponent<Renderer>().sharedMaterial.color : unbuiltColor;
            lineRenderer.startWidth = width;
            lineRenderer.endWidth = width;

            lineRenderer.SetGreatCircleArc(nodeA.transform.position, nodeB.transform.position, 5, 20.5f);
            lineRenderer.enabled = true;
        }

        hovered = false;
    }
}
