using UnityEngine;
using UnityEngine.InputSystem;

public class Movement : MonoBehaviour
{
    private Rigidbody2D body;
    private SpriteRenderer sprite_renderer;

    private string id;

    public float initialX = 0;
    public float initialY = 0;
    public float speed = 0.1f;

    static string activeId = "Snail";
    static bool canChangeActiveId = true;

    // Start is called once before the first execution of Update after the MonoBehaviour is created
    void Start()
    {
        this.body = GetComponent<Rigidbody2D>();
        this.sprite_renderer = GetComponent<SpriteRenderer>();

        this.id = gameObject.name;

        this.body.transform.position = new Vector2(this.initialX, this.initialY);

        this.ActiveChange();
    }

    // Update is called once per frame
    void Update()
    {
        bool activated = this.IsActive();

        if (Keyboard.current.rightArrowKey.isPressed)
        {
            if (!activated) return;

            this.body.MovePosition(this.body.position + new Vector2(this.speed, 0));
        }

        if (Keyboard.current.leftArrowKey.isPressed)
        {
            if (!activated) return;

            this.body.MovePosition(this.body.position + new Vector2(-this.speed, 0));
        }

        if (Keyboard.current.downArrowKey.isPressed)
        {
            this.ActiveChange();

            if (!Movement.canChangeActiveId) return;
            Movement.canChangeActiveId = false;

            if (Movement.activeId == "Snail") Movement.activeId = "Ghost";
            else if (Movement.activeId == "Ghost") Movement.activeId = "Snail";

            this.ActiveChange();
        } else
        {
            Movement.canChangeActiveId = true;
        }
    }

    void ActiveChange()
    {
        this.sprite_renderer.color = new Color(1f, 1f, 1f, this.IsActive() ? 1f : 0.5f);
    }

    bool IsActive()
    {
        return this.id == Movement.activeId; 
    }
}
