using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.InputSystem;
using System.Linq;

[RequireComponent(typeof(PlayerInput))]
public class PlayerMovement : MonoBehaviour
{
    public PlayerAnimationHandler animationHandler;
    public float moveSpeed = 5f;
    private Rigidbody2D rb;

    private bool right = false;

    private bool vibrate = false;
    [SerializeField] private float stepCooldown = 0.05f;
    [SerializeField] private float stepVibrationTime = 0.05f;

    [SerializeField] private GameObject rumble;

    [Header("Whipping")]
    [SerializeField]
    RopeWhipAttack whipAttack;

    [SerializeField]
    private float whipMoveSpeed = 25f;

    [SerializeField]
    private float maxWhipMoveSpeed = 30f;

    private PlayerInput playerInput;

    private void Start()
    {
        rb = GetComponent<Rigidbody2D>();
        playerInput = GetComponent<PlayerInput>();

        if (gameObject.name == "Player2")
        {
            playerInput.useArrowKeys = true;
        }

        StartCoroutine(ToggleWithDelay());
    }

    void Update()
    {
        if (playerInput.movement != Vector2.zero)
        {
            RumbleWalk();
            animationHandler.Run();
        }
    }
    private void FixedUpdate()
    {
        if (whipAttack.IsBeingWhipped)
        {
            //float sign = Vector2.Dot((whipAttack.joint.position - whipAttack.otherPlayerAttack.joint.position).normalized, movement.normalized);

            Vector2 ropeDir = whipAttack.otherPlayerAttack.joint.position - whipAttack.joint.position;
            Vector2 tangent = new Vector2(-ropeDir.y, ropeDir.x).normalized;

            rb.AddForce(Vector2.Dot(playerInput.movement, tangent) * tangent * whipMoveSpeed);
            rb.velocity = Vector2.ClampMagnitude(rb.velocity, maxWhipMoveSpeed);
        }
        else if (whipAttack.IsWhippingOtherPlayer)
        {
            playerInput.movement = Vector2.zero;
        }
        else
        {
            rb.AddForce(playerInput.movement * moveSpeed);
        }

    }
    private void RumbleWalk()
    {
        if (vibrate && playerInput.controller != null)
        {
            if (right)
            {
                rumble.GetComponent<RumbleManager>().RumblePulse(0.0f, 0.004f, stepVibrationTime, playerInput.PlayerNum);
                right = false;
            }
            else if (!right)
            {
                rumble.GetComponent<RumbleManager>().RumblePulse(0.004f, 0.0f, stepVibrationTime, playerInput.PlayerNum);
                right = true;
            }
            vibrate = false;
        }
    }
    private IEnumerator ToggleWithDelay()
    {
        while (true)
        {
            vibrate = !vibrate;
            yield return new WaitForSeconds(stepCooldown);
        }
    }
}