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

public class CustomVertCollider : MonoBehaviour
{

    Vector3[] debugContactPoints;
    public Movement playerMovement;
    public Vector3 horizResolveVector; // horizontal collision are checked for the vertical collider as to defend against being able to clip the vertical collider into walls when jumping
    public Vector3 vertResolveVector;
    public Transform playerTransform;
    public float floorHeight;
    public Vector3 offset;

    public float resolveTranslationStrength;
    private void OnCollisionEnter(Collision collision)
    {
        // horizontal collision resolving:

        ContactPoint[] contactPoints = new ContactPoint[collision.contactCount];
        collision.GetContacts(contactPoints);

        debugContactPoints = new Vector3[contactPoints.Length];
        for (int i = 0; i < contactPoints.Length; ++i)
        {
            debugContactPoints[i] = contactPoints[i].point;
        }


        Vector3 averageContactPoint = Vector3.zero;
        Vector3 resolveVector = Vector3.zero;
        if (contactPoints.Length > 0)
        {
            for (int i = 0; i < contactPoints.Length; ++i)
            {
                averageContactPoint += contactPoints[i].point;
            }
            averageContactPoint /= contactPoints.Length;

            resolveVector = averageContactPoint - transform.position;
        }
        resolveVector.y = 0;

        horizResolveVector = resolveVector;


        vertResolveVector = Vector3.down;
    }
    private void OnCollisionStay(Collision collision)
    {

        //transform.position += Vector3.up * resolveTranslationStrength * Time.deltaTime; 

        vertResolveVector = Vector3.down;

    }


    private void OnCollisionExit(Collision collision)
    {
        debugContactPoints = null;
        //horizResolveVector = Vector3.zero;
        vertResolveVector = Vector3.zero;
    }


    private void OnDrawGizmos()
    {
        if (debugContactPoints == null || debugContactPoints.Length == 0)
            return;

        Gizmos.color = Color.blue;
        foreach (Vector3 point in debugContactPoints)
        {
            Gizmos.DrawSphere(point, 0.05f);
        }

        Gizmos.color = Color.yellow;
        Gizmos.DrawLine(playerTransform.position, playerTransform.position + playerMovement.velocity);
        Gizmos.color = Color.green;
        Gizmos.DrawLine(playerTransform.position, playerTransform.position + vertResolveVector);
    }


    public float extrapolateDistance;

    void Update()
    {
        Vector3 velocityDir = playerMovement.velocity.normalized;
        velocityDir.y = velocityDir.y > 0 ? 0 : velocityDir.y;
        transform.position = (playerTransform.position + offset) + velocityDir * extrapolateDistance;
    }
}
