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

public class AICustomer : MonoBehaviour
{
    public FXTrigger eatingFX;

    public static bool newCustomerNeeded;

    public Sprite eatingSprite;
    public float disappearAfterEatingDistance = 6f;
    public float flipThreshold = 0.1f;

    private Cargo cargo;
    private SpriteRenderer rend;

    void Start()
    {
        newCustomerNeeded = false;
        cargo = GetComponent<Cargo>();
        rend = GetComponent<SpriteRenderer>();
    }

    private void FlipTowardPlayer()
    {
        if (Player.playerTransform.position.x > transform.position.x + flipThreshold)
        {
            rend.flipX = false;
        }
        else if (Player.playerTransform.position.x < transform.position.x - flipThreshold)
        {
            rend.flipX = true;
        }
    }

    private void FlipAwayFromPlayer()
    {
        if (Player.playerTransform.position.x > transform.position.x + flipThreshold)
        {
            rend.flipX = true;
        }
        else if (Player.playerTransform.position.x < transform.position.x - flipThreshold)
        {
            rend.flipX = false;
        }
    }

    private bool AtDisappearDistance()
    {
        return Vector2.Distance(Player.playerTransform.position, transform.position) >= disappearAfterEatingDistance;
    }

    void Update()
    {
        if (cargo.type == Cargo.ItemType.Pizza)
        {
            FlipAwayFromPlayer();
            if (AtDisappearDistance())
            {
                Destroy(gameObject);
            }
        }
        else if (cargo.type == Cargo.ItemType.Cash)
        {
            FlipTowardPlayer();
        }
    }

    void OnTriggerEnter2D(Collider2D other)
    {
        if (cargo.type == Cargo.ItemType.Pizza)
            return;

        if (other.gameObject.CompareTag("Player") && cargo.type == Cargo.ItemType.Cash)
        {
            Cargo playerCargo = other.gameObject.GetComponent<Cargo>();

            if (playerCargo.type == Cargo.ItemType.Pizza)
            {
                newCustomerNeeded = true;

                playerCargo.type = Cargo.ItemType.Cash;
                cargo.type = Cargo.ItemType.Pizza;

                eatingFX.Trigger(transform);
                rend.sprite = eatingSprite;
                float awayX = Mathf.Sign(transform.position.x - Player.playerTransform.position.x);
                transform.position += new Vector3(awayX * 0.75f, 0, 0);
            }
        }
    }

}
