using UnityEngine;
using UnityEngine.InputSystem;

public class PlayerController : MonoBehaviour
{
    public float speed = 3f;
    public bool isGoingLeft = false;
    public bool canActivateButton = false;
    public bool canPickupBox = false;
    public string defaultLayer = "Player";
    public string inactiveLayer = "PlayerNotPlaying";

    private SpriteRenderer sprite_renderer;
    private Collider2D collider;

    void Start()
    {
        this.sprite_renderer = GetComponent<SpriteRenderer>();
        this.collider = GetComponent<Collider2D>();

        GameManager.instance.AttachPlayerController(this.name, this);

        if (this.IsActive()) this.OnActivate();
        else this.OnDeactivate();
    }

    void Update()
    {
        this.sprite_renderer.color = new Color(1f, 1f, 1f, this.IsActive() ? 1f : 0.5f);
        this.sprite_renderer.sortingOrder = this.IsActive() ? 2 : 1;
        this.sprite_renderer.flipX = this.isGoingLeft;

        if (Keyboard.current.rightArrowKey.isPressed && this.IsActive())
        {
            this.gameObject.transform.position += new Vector3(speed * Time.deltaTime, 0, 0);
            this.isGoingLeft = false;
        }

        if (Keyboard.current.leftArrowKey.isPressed && this.IsActive())
        {
            this.gameObject.transform.position += new Vector3(-speed * Time.deltaTime, 0, 0);
            this.isGoingLeft = true;
        }
    }

    public bool IsActive()
    {
        return this.name == GameManager.instance.GetActivePlayerId();
    }

    public bool IsTouching(Collider2D collider)
    {
        return this.collider.IsTouching(collider);
    }

    public void OnActivate()
    {
        this.gameObject.layer = LayerMask.NameToLayer(this.defaultLayer);
    }

    public void OnDeactivate()
    {
        this.gameObject.layer = LayerMask.NameToLayer(this.inactiveLayer);
    }

    public Vector3 GetPosition()
    {
        return this.transform.position;
    }
}
