using UnityEngine;
using System.Collections.Generic;

[ExecuteAlways]
public class Node : MonoBehaviour
{
    [Range(-1, 1)]
    [SerializeField]
    public int Owner = -1;
    public Material materialOwnerSelf, materialOwnerOther, materialOwnerNone;


    void Awake()
    {
        UpdateColor();
    }

    // Start is called once before the first execution of Update after the MonoBehaviour is created
    void Start()
    {

    }

    // Update is called once per frame
    void Update()
    {
        UpdateTransform();
    }

    private void OnValidate()
    {
        UpdateColor();
        UpdateTransform();
    }

    private void OnDestroy()
    {
        GameManager gm = FindFirstObjectByType<GameManager>();
        
        List<GameManager.Connection> looseConnections = gm.connections.FindAll(c => c.nodeA == this || c.nodeB == this);

        foreach(GameManager.Connection c in looseConnections)
        {
            DestroyImmediate(c.lineRenderer.gameObject);
            gm.connections.Remove(c);
        }
        
        gm.FetchAllNodes();
    }

    public void UpdateTransform()
    {
        transform.localPosition = transform.localPosition.normalized * 20f;
        if(transform.position != Vector3.zero) 
            transform.forward = transform.position;
    }

    public void UpdateColor()
    {
        switch (Owner)
        {
            case -1: transform.GetChild(0).GetComponent<Renderer>().sharedMaterial = materialOwnerNone; break;
            case 0: transform.GetChild(0).GetComponent<Renderer>().sharedMaterial = materialOwnerSelf; break;
            case 1: transform.GetChild(0).GetComponent<Renderer>().sharedMaterial = materialOwnerOther; break;
        }
    }

}
