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

public class MovementManager : MonoBehaviour
{ 

    private float speed = 400f;
    public float slidingSpeed = 1000f;
    private bool IsSideScrolling = true;
    private bool isActing = false;
    private float actingCooldown = 0.5f;
    private bool isSliding = false;
    private Vector2 slidingDirection = Vector2.zero;
    private bool isHiding = false;
    public bool IsHiding
    {
        get
        {
            return isHiding;
        }
    }
    public bool canPlace = false;
    public bool canTake = false;
    private bool isShooting = false;
    public bool directionRight = true;
    public bool hasShell = true;
    private float shootCooldownTimer = 1f;

    private ShellActions shell;
    private Rigidbody2D rb;
    private SpriteRenderer sprite;
    private PlayerAnimationHandler handler;
    private PlayerDialogueManager pdm;
    public GameObject spit;
    private Transform mouth;

    // Start is called before the first frame update
    void Start()
    {
        rb = GetComponent<Rigidbody2D>();
        shell = GetComponent<ShellActions>();
        sprite = GetComponent<SpriteRenderer>();
        handler = new PlayerAnimationHandler(gameObject);
        pdm = GetComponentInChildren<PlayerDialogueManager>();
        mouth = transform.Find("Mouth");
    }
    
    // Update is called once per frame
    void Update()
    {
        // popup pausa
        if (Input.GetKeyDown(KeyCode.R)) {
            SceneManager.LoadScene(SceneManager.GetActiveScene().name);
        }

        if (Input.GetKeyDown(KeyCode.E))
        {

           if (canPlace && !canTake)
           {
               Place();
           }
            else if (canTake && !canPlace)
           {
               Take();
           }
         }
        if (!isActing && !isSliding)
        {
            if (!isHiding)
            {
                Movement();
                Shoot();
            }
            Hide();
        }
        else if (isSliding)
        {
            rb.velocity = slidingDirection * slidingSpeed;
            rb.velocity *= directionRight ? 1 : -1;
        }

        sprite.enabled = !isHiding;
        Physics2D.IgnoreLayerCollision(8, 9, isHiding);

        if (rb.velocity.x == 0)
        {
            Debug.Log("fermo");
            handler.SetIdle();
        } 
        else if (rb.velocity.x != 0 && rb.velocity.y == 0)
        {
            handler.SetMovement();
            Debug.Log("movimento laterale");
        }


    }

    private void Place()
    {

            if (!isActing)
            {
               
                StartCoroutine("ActingCooldown");
                hasShell = false;
                shell.Place();

            }

    }

    private void Take ()
    {
        if (!isActing)
        {
            StartCoroutine("ActingCooldown");
            hasShell = true;
            shell.Take();

        }
    }

    private void Shoot()
    {
        if (Input.GetKeyDown(KeyCode.Space) && !isShooting)
        {
            StartCoroutine(ShootCooldown());
            var projectile = Instantiate(spit);
            projectile.GetComponent<ProjectileBehaviour>().Shoot(mouth.position, directionRight? Vector2.right : Vector2.left);
        }
      
    }

    private IEnumerator ShootCooldown()
    {
        isShooting = true;
        yield return null;
        var t = shootCooldownTimer;
        while (t >= 0)
        {
            t -= Time.deltaTime;
            yield return null;

        }
        isShooting = false;
        yield return null;

    }

    private void Hide()
    {
        if (Input.GetKeyDown(KeyCode.Q) && hasShell)
        {
            isHiding = true;
            hasShell = false;
            shell.Hide();
        }
        else if (Input.GetKeyUp(KeyCode.Q) && !hasShell && isHiding)
        {
            isHiding = false;
            hasShell = true;
            shell.RemoveHide();
        }
    }

    private IEnumerator ActingCooldown()
    {
        var t = actingCooldown;
        isActing = true;
        while (t >= 0)
        {
            t -= Time.deltaTime;
            yield return null;
        }
        isActing = false;
        yield return null;

    }


    private void Movement()
    {
        rb.velocity = Vector2.zero;
        if (Input.GetKey(KeyCode.W) && !IsSideScrolling)
        {
            rb.velocity = Vector2.up * speed;
        }
        else if (Input.GetKey(KeyCode.S) && !IsSideScrolling)
        {
            rb.velocity = Vector2.down * speed;
        }
        else if (Input.GetKey(KeyCode.A))
        {
            directionRight = false;
            rb.velocity = Vector2.left * speed;
 
        }
        else if (Input.GetKey(KeyCode.D))
        {
            directionRight = true;
            rb.velocity = Vector2.right * speed;
        }
    
        transform.localScale = new Vector3( directionRight ? Mathf.Abs(transform.localScale.x) : Mathf.Abs(transform.localScale.x) * -1f, transform.localScale.y, transform.localScale.z);
    }


    private void OnCollisionEnter2D(Collision2D collision)
    {
        if (collision.gameObject.name == "OffShell" && !isHiding)
        {
            isSliding = true;
        }
    }

    private void OnCollisionStay2D(Collision2D collision)
    {
        if (collision.gameObject.name == "OffShell" && !isHiding)
        {
            if (isSliding)
            {
                var temp = (transform.position - collision.transform.position);

                slidingDirection = -Vector2.Perpendicular(temp.normalized);


            }
        }
    }

    private void OnCollisionExit2D(Collision2D collision)
    {
         if (collision.gameObject.name == "OffShell" && !isHiding)
        {
            if (isSliding)
            {
                isSliding = false;
                rb.velocity = Vector2.zero;
            }
        }
    }

    private void OnTriggerStay2D(Collider2D collision)
    {
        if (collision.gameObject.name == "OffShell")
        {
            canTake = true;
            pdm.SetDialogueBox("E");
        }
    }


    private void OnTriggerExit2D(Collider2D collision)
    {
        if (collision.gameObject.name == "OffShell")
        {
            canTake = false;
            pdm.CloseDialogueBox();

        }
    }





}
