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

public class CharControllerMod : MonoBehaviour
{

    public float maxSpeed = 3.4f;
    public float jumpHeight = 6.5f;
    public float gravityScale = 1.5f;
    public Camera mainCamera;


    bool facingRight = true;
    public bool grounded = false;
    Vector3 cameraPos;
    float moveDirection = 0;
    Rigidbody2D rb;
    CapsuleCollider2D mainCollider;
    CapsuleCollider2D friction;
    Transform t;   

    
    // Start is called before the first frame update
    void Start()
    {
        t = transform;
        rb = GetComponent<Rigidbody2D>();
        mainCollider = GetComponent<CapsuleCollider2D>();
        friction = GetComponent<CapsuleCollider2D>();
        rb.freezeRotation = true;
        rb.gravityScale = gravityScale;
        
        if(mainCamera)
        {
            cameraPos = mainCamera.transform.position;
        }

    }

    // Update is called once per frame
    void Update()
    {
    
        //if(grounded || Mathf.Abs(rb.velocity.x) > 0.01f)
        moveDirection = Input.GetAxisRaw("Horizontal");

        if(moveDirection != 0)
        {
             if (moveDirection > 0 && !facingRight)
            {
                facingRight = true;
                t.localScale = new Vector3(Mathf.Abs(t.localScale.x), t.localScale.y, transform.localScale.z);
            }
            if (moveDirection < 0 && facingRight)
            {
                facingRight = false;
                t.localScale = new Vector3(-Mathf.Abs(t.localScale.x), t.localScale.y, t.localScale.z);
            }
        }

        
        if(Input.GetButtonDown("Jump") && grounded)
        {
            rb.velocity = new Vector2(rb.velocity.x, jumpHeight);
        }

        if (mainCamera)
        {
            mainCamera.transform.position = new Vector3(t.position.x, t.position.y, cameraPos.z);
        }
    }

    void FixedUpdate()
    {

        Bounds colliderBounds = mainCollider.bounds;
        float colliderRadius = mainCollider.size.x * 0.4f * Mathf.Abs(transform.localScale.x);
        Vector3 groundCheckPos = colliderBounds.min + new Vector3(colliderBounds.size.x * 0.5f, colliderRadius * 0.9f, 0);

        Collider2D[] colliders = Physics2D.OverlapCircleAll(groundCheckPos, colliderRadius);

        grounded = false;
        if (colliders.Length > 2)
        {
            foreach (Collider2D hit in colliders){
                if (hit != mainCollider){
                    grounded = true;
                    break;
                }
            }
        }

        rb.velocity = new Vector2(moveDirection * maxSpeed, rb.velocity.y);

        Debug.DrawLine(groundCheckPos, groundCheckPos - new Vector3(0, colliderRadius, 0), grounded ? Color.green : Color.red);
        Debug.DrawLine(groundCheckPos, groundCheckPos - new Vector3(colliderRadius, 0, 0), grounded ? Color.green : Color.red);
    }
}
