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

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

    private bool right = false;

    [Header("Whipping")]
    [SerializeField]
    RopeWhipAttack whipAttack;
    public float whipSmashSpeed = 2f;
    public float whipSmashDamageMult = 2f;

    [SerializeField]
    private float whipMoveSpeed = 25f;

    [SerializeField]
    private float maxWhipMoveSpeed = 30f;

    private PlayerInput playerInput;

    private HealthComponent hp;
    private PlayerCollideAttack attack;

    private void Start()
    {
        rb = GetComponent<Rigidbody2D>();
        playerInput = GetComponent<PlayerInput>();
        hp = GetComponent<HealthComponent>();
        attack = GetComponent<PlayerCollideAttack>();

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

        if (playerInput.controller != null)
        {
            var pad = (DualShockGamepad)Gamepad.all.ElementAtOrDefault(playerInput.PlayerNum);
            if (pad == null) return;

            if (playerInput.PlayerNum == 1)
                pad.SetLightBarColor(Color.red);
        }
    }

    private void Update()
    {
        if (playerInput.movement != Vector2.zero)
            animationHandler.Run(true);
        else
            animationHandler.Run(false);
    }

    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);
        }

    }

    void OnCollisionStay2D(Collision2D collision)
    {
        if (collision.collider.gameObject.CompareTag("Enemy"))
        { // Other object is an enemy
            if (whipAttack.IsBeingWhipped && rb.velocity.magnitude > attack.speedYouNeedToNotTakeDamageFromRammingOrSomtmh) {
                // collision.collider.gameObject.GetComponent<HealthComponent>().TakeDamage(rb.velocity.magnitude * whipSmashDamageMult);
            } else {
                hp.TakeDamage(1f);
            }
        }
    }
}