﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml.Linq;

namespace Afas.ProfitClient.Filters
{
    /// <summary>
    /// Fluent AFAS Profit Filter for GetConnector. Usage: new ProfitXmlFilter().AddFilter().AddRestriction("myfield", ComparerType.Equal, 1).Create();
    /// </summary>
    public class ProfitXmlFilter : IFluentFilter
    {
        private Dictionary<string, List<XElement>> filters = new Dictionary<string,List<XElement>>();
        private string currentFilterId;

        #region Filter methods
        /// <summary>
        /// Add a new filter
        /// </summary>
        /// <param name="id">unique id of filter</param>
        /// <returns></returns>
        public IFluentFilter AddFilter()
        {
            var newFilterId = (filters.Count + 1).ToString();
            filters.Add(newFilterId, new List<XElement>());
            currentFilterId = newFilterId;

            return this;
        }

        /// <summary>
        /// Add a new field restriction
        /// </summary>
        /// <param name="fieldId"></param>
        /// <param name="compareType"></param>
        /// <param name="value"></param>
        /// <returns></returns>
        public IFluentFilter AddRestriction(string fieldId, ComparerType compareType, object value)
        {
            filters[currentFilterId].Add(new XElement("Field", value, new XAttribute("FieldId", fieldId), new XAttribute("OperatorType", (int)compareType)));
            return this;
        }

        /// <summary>
        /// Return the actual xml string
        /// </summary>
        /// <returns></returns>
        public string Create()
        {
            var xmlFilter = new XElement("Filters");
            foreach (var filter in filters)
            {
                xmlFilter.Add(new XElement("Filter", new XAttribute("FilterId", filter.Key), filter.Value));
            }
            return xmlFilter.ToString(SaveOptions.DisableFormatting);
        }

        #endregion
    }
}