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

public class LiquidPourer : MonoBehaviour
{
    [SerializeField] private HandController _handController;
    [SerializeField] private KeyCode _pourKey = KeyCode.E;

    void Update()
    {
        if (!Input.GetKeyDown(_pourKey)) return;

        Transform right = _handController.RightHeldObject;
        Transform left = _handController.LeftHeldObject;

        if (right == null || left == null) return;
        if (!right.CompareTag("Liquid") || !left.CompareTag("Liquid")) return;

        LiquidContainer containerRight = right.GetComponent<LiquidContainer>()
            ?? right.GetComponentInParent<LiquidContainer>()
            ?? right.GetComponentInChildren<LiquidContainer>();

        LiquidContainer containerLeft = left.GetComponent<LiquidContainer>()
            ?? left.GetComponentInParent<LiquidContainer>()
            ?? left.GetComponentInChildren<LiquidContainer>();

        if (containerRight == null || containerLeft == null) return;

        LiquidContainer source = null;
        LiquidContainer target = null;

        if (!containerRight.IsEmpty() && !containerLeft.IsFull())
        {
            source = containerRight;
            target = containerLeft;
        }
        else if (!containerLeft.IsEmpty() && !containerRight.IsFull())
        {
            source = containerLeft;
            target = containerRight;
        }

        if (source == null || target == null) return;

        float sourceRealLiters = source.amount * source.capacity;
        float targetFreeSpace = (1f - target.amount) * target.capacity;

        float transferLiters = Mathf.Min(sourceRealLiters, targetFreeSpace);
        if (transferLiters <= 0f) return;

        float sourceRemoveAmount = transferLiters / source.capacity;
        float targetAddAmount = transferLiters / target.capacity;

        Color pouringColor = source.color;
        float pouringDensity = source.density;
        LiquidContainer.LiquidType pouringType = source.liquidType;

        source.RemoveLiquid(sourceRemoveAmount);
        target.AddLiquid(pouringColor, targetAddAmount, pouringDensity, pouringType);
    }
}
