using System;

namespace GitHub.DistributedTask.Expressions2.Sdk.Functions
{
    internal sealed class Contains : Function
    {
        protected sealed override Boolean TraceFullyRealized => false;

        protected sealed override Object EvaluateCore(
            EvaluationContext context,
            out ResultMemory resultMemory)
        {
            resultMemory = null;
            var left = Parameters[0].Evaluate(context);
            if (left.IsPrimitive)
            {
                var leftString = left.ConvertToString();

                var right = Parameters[1].Evaluate(context);
                if (right.IsPrimitive)
                {
                    var rightString = right.ConvertToString();
                    return leftString.IndexOf(rightString, StringComparison.OrdinalIgnoreCase) >= 0;
                }
            }
            else if (left.TryGetCollectionInterface(out var collection) &&
                collection is IReadOnlyArray array &&
                array.Count > 0)
            {
                var right = Parameters[1].Evaluate(context);
                foreach (var item in array)
                {
                    var itemResult = EvaluationResult.CreateIntermediateResult(context, item);
                    if (right.AbstractEqual(itemResult))
                    {
                        return true;
                    }
                }
            }

            return false;
        }
    }
}
