using UnityEngine;

public class PlayerRotate : MonoBehaviour {
    [SerializeField] private float rotateStep = 15f;
    [SerializeField] private LayerMask groundMask;

    [Space]
    [SerializeField] private GameObject placer;
    [SerializeField] private GameObject casteller;
    private float _pieceRotation;
    private bool _canPlace;

    private Vector2Int _pressPosition;
    private bool _dead;

    private void Update() {
        if (_dead)
            return;

        Debug.Assert(Camera.main != null, "Camera.main != null");

        SetPlacerPosition();

        _pieceRotation += Input.mouseScrollDelta.y * rotateStep;
        placer.transform.rotation = Quaternion.Euler(0f, _pieceRotation, 0f);

        CheckPress();
    }

    private void SetPlacerPosition() {
        Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
        if(Physics.Raycast(ray, out RaycastHit hit, 300f, groundMask)){
            if (Vector3.Dot(hit.normal, Vector3.up) >= .9f) {
                placer.SetActive(true);
                placer.transform.position = hit.point;
                _canPlace = true;
                return;
            }
        }

        _canPlace = false;
        placer.SetActive(false);
    }

    private void CheckPress() {
        Vector2Int pressPosition = new((int)Input.mousePosition.x, (int)Input.mousePosition.y);

        if (Input.GetMouseButtonDown(0)){
            _pressPosition = pressPosition;
        }

        if (Input.GetMouseButtonUp(0) && _pressPosition == pressPosition && _canPlace) {
            FindAnyObjectByType<CameraHeight>().SetHeight(placer.transform.position.y);
            FindAnyObjectByType<Interface>().PlacePiece();
            Instantiate(casteller, placer.transform.position, Quaternion.Euler(0f, _pieceRotation, 0f));
        }
    }

    public void Die() {
        placer.SetActive(false);
        _dead = true;
    }
}
