using UnityEngine;
namespace XenseAR {


public class DistanceLoadAlgorithm : ILoadingTargetAlgorithm
{
    const float INTERESTEDDISTANCE = 18;
    const float DISPOSE_DISTANCE = 30;
    const float REQUIRE_HEIGHT = 3;
    GameObject ARCamera;
    private float interestedDistance = INTERESTEDDISTANCE; //Lets user modify this value base on their experience, default value is 18 time
    private float disPoseDistance = DISPOSE_DISTANCE;
    private float requireHeight = REQUIRE_HEIGHT;
    public DistanceLoadAlgorithm(float interestedDistance = INTERESTEDDISTANCE, float disPoseDistance = DISPOSE_DISTANCE, float requireHeight = REQUIRE_HEIGHT)
    {
        ARCamera = Camera.main.gameObject;
        if (interestedDistance > 0)
            this.interestedDistance = interestedDistance;
        if (disPoseDistance > 0)
            this.disPoseDistance = disPoseDistance;
        if (requireHeight > 0)
            this.requireHeight = requireHeight;
    }

    public DistanceLoadAlgorithm(AnchoringTarget target)
    {
        ARCamera = Camera.main.gameObject;
        if (target.interestedDistance > 0)
            this.interestedDistance = target.interestedDistance;
        else
            this.interestedDistance = INTERESTEDDISTANCE * Mathf.Max(target.boundSize.x, target.boundSize.y, target.boundSize.z);

        if (target.disposeDistance > 0)
            this.disPoseDistance = target.disposeDistance;
        else
            this.disPoseDistance = DISPOSE_DISTANCE * Mathf.Max(target.boundSize.x, target.boundSize.y, target.boundSize.z);

        if (target.requireHeight > 0)
            this.requireHeight = target.requireHeight;
        else
            this.requireHeight = REQUIRE_HEIGHT;
    }


    public bool IsNeedLoad(AnchoringTarget target, Transform transform)
    {
        if (requireHeight > 0)
        {
            if (ARCamera.transform.position.y > transform.position.y+ requireHeight)
                return false;
            if (ARCamera.transform.position.y < transform.position.y - requireHeight)
                return false;
        }

        //get distance from camera to the root point of target
        float distance = Vector3.Distance(ARCamera.transform.position, transform.position);

        if (distance <= interestedDistance)
            return true;

        //if the distance is greater than the interested distance then should not show the target
        return false;
    }
    public bool IsNeedDispose(AnchoringTarget target, Transform transform)
    {
        float distance = Vector3.Distance(ARCamera.transform.position, transform.position);

        if (distance >= disPoseDistance)
            return true;

        if (requireHeight > 0)
        {
            if (ARCamera.transform.position.y < transform.position.y- requireHeight)
                return true;
            if (ARCamera.transform.position.y > transform.position.y + requireHeight)
                return true;
        }
        return false;
    }
}}
