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

public class Ghost : MonoBehaviour {
    private Transform visual;

    private void Start() {
        RefreshVisual();

        GroundGridControllerScript.Instance.OnSelectedChanged += Instance_InSelectedChanged;
    }

    private void Instance_InSelectedChanged(object sender, System.EventArgs args) {
        RefreshVisual();
    }

    private void LateUpdate() {
        Vector3 targetPosition = GroundGridControllerScript.Instance.GetMouseWorldSnappedPosition();
        targetPosition.y = 1f;
        Vector2Int rotationOffset = GroundGridControllerScript.Instance.GetPlacedObjectRotationOffset();

        transform.position = Vector3.Lerp(transform.position, targetPosition + new Vector3(rotationOffset.x, 0, rotationOffset.y) * GroundGridControllerScript.Instance.GetGridXZ().GetCellSize(), Time.deltaTime * 15f);
        transform.rotation = Quaternion.Lerp(transform.rotation, GroundGridControllerScript.Instance.GetPlacedObjectRotation(), Time.deltaTime * 15f);
    }

    public void RefreshVisual() {
        if (visual != null) {
            Destroy(visual.gameObject);
        }

        PlacedObjectTypeSO placedObjectTypeSO = GroundGridControllerScript.Instance.GetActiveObjectTypeSO();

        if (placedObjectTypeSO != null) {
            visual = Instantiate(placedObjectTypeSO.visual, Vector3.zero, Quaternion.identity);
            visual.parent = transform;
            visual.localPosition = Vector3.zero;
            visual.localEulerAngles = Vector3.zero;
            SetLayerRecursive(visual.gameObject, 7);
        }
    }

    private void SetLayerRecursive(GameObject targetGameObject, int layer) {
        targetGameObject.layer = layer;
        foreach (Transform child in targetGameObject.transform) {
            SetLayerRecursive(child.gameObject, layer);
        }
    }
}
