/*-------------------------------------------------------------------------
 * 功能描述：ParseInstance
 * 作者：xulisong
 * 创建时间： 2019/6/13 15:04:06
 * 版本号：v1.0
 *  -------------------------------------------------------------------------*/

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace RevitExport
{
    /*
     * 最好由导出类控制，导出的开始和结束。这样有一个好处是可以挂接多个解析类。
     */
    /// <summary>
    /// 解析实例
    /// </summary>
    public class ParseInstance<C> where C:ParseContext
    {
        public ParseInstance(C context,List<IParseElement<C>> parsers)
        {
            Context = context;
            Parsers = parsers;
        }
        protected List<IParseElement<C>> Parsers { get; set; }
        
        protected virtual IParseElement<C> GetMatchParser(ElementWrapper wrapper)
        {
            var currentParse = Parsers.FirstOrDefault(p => p.Match(wrapper));
            return currentParse;
        }
        #region 解析元素相关
        public virtual void ParseElement(object sender, ExportArgs e)
        {
            if (!Parsers.Any())
                return;
            ElementWrapper element = e.ElementWrapper;
            var currentParse = GetMatchParser(element);
            if (currentParse != null)
            {
                currentParse.Parse(element, Context);
            }
        }

        /// <summary>
        /// 当前解析上下文
        /// </summary>
        public C Context { get;protected set; }

        /// <summary>
        /// 解析数据
        /// </summary>
        /// <param name="export"></param>
        /// <returns></returns>
        public virtual bool Parse(ExportInstance export)
        {
            BindingExport(this,export);
            Context.Export = export;
            return export.Export();
        }

        public static void BindingExport(ParseInstance<C> instance, ExportInstance export)
        {
            export.ParseElement -= instance.ParseElement;
            export.ParseElement += instance.ParseElement;
        }
        #endregion
    }
}
