﻿using System;
using Syntaxiom.Symbols.Factories;

namespace Syntaxiom.Symbols.Filters
{
    public class UrlEncode : Filter
    {
        private readonly ISymbolFactory _symbolFactory;
        private readonly ISymbol _source;

        public UrlEncode(ISymbolFactory symbolFactory, ISymbol source)
        {
            _symbolFactory = symbolFactory;
            _source = source;
        }

        public override ISymbol ResolveReference(IEvaluationContext context)
        {
            var source = _source?.ResolveReference(context) as ISymbol<string>;
            var sourceValue = source?.ResolveValue(context);

            return string.IsNullOrEmpty(sourceValue) 
                ? _source 
                : _symbolFactory.CreateConstant(Uri.EscapeDataString(sourceValue));
        }
    }
}