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

public class Turret : MonoBehaviour
{
    public float speed = 10.0f;
    public float distance = 2.0f;
    public bool isHorizontal = false;

    float startX;
    float startY;
    ChargeCounter chargeCounter;

    void Start()
    {
        startX = transform.position.x;
        startY = transform.position.y;
        chargeCounter = GameObject.FindWithTag("Charge Counter").GetComponent<ChargeCounter>();
    }

    void Update()
    {
        Vector3 movementVector = getMovementVector();

        if (allowMovement(movementVector)) moveTurret(movementVector);
    }

    bool allowMovement(Vector3 movementVector)
    {
        bool moveUp = movementVector.y > 0;
        bool moveDown = movementVector.y < 0;
        bool moveRight = movementVector.x > 0;
        bool moveLeft = movementVector.x < 0;

        if (moveUp && transform.position.y >= startY + distance) return false;
        if (moveDown && transform.position.y <= startY - distance) return false;
        if (moveRight && transform.position.x >= startX + distance) return false;
        if (moveLeft && transform.position.x <= startX - distance) return false;
        return true;
    }

    Vector3 getMovementVector()
    {
        if (chargeCounter.IsLevelWon()) return Vector3.zero;
        if (isHorizontal && Input.GetAxisRaw("Horizontal") == 0) return Vector3.zero;
        if (!isHorizontal && Input.GetAxisRaw("Vertical") == 0) return Vector3.zero;

        float x = isHorizontal ? Input.GetAxis("Horizontal") : 0;
        float y = isHorizontal ? 0 : Input.GetAxis("Vertical");

        return new Vector3(x, y, 0);
    }

    void moveTurret(Vector3 movementVector)
    {
        transform.position += movementVector * speed * Time.deltaTime;
    }

    void OnDrawGizmosSelected()
    {
        Vector3 offset = isHorizontal ? new Vector3(distance, 0, 0) : new Vector3(0, distance, 0);

        Gizmos.color = Color.red;
        Gizmos.DrawLine(transform.position - offset, transform.position + offset);
    }
}
