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

namespace ZionRobot.Models.Search
{
    public class Result : System.Xml.XmlDocument, IDisposable
    {
        private System.Xml.XmlNode root;
        public System.Xml.XmlNode Root { get; }

        public List<Models.Search.Element> Elements;

        public void Dispose()
        {
            if (Elements != null)
                foreach (Models.Search.Element e in Elements)
                    e.Dispose();

            GC.SuppressFinalize(this);
        }

        public Result()
        {
            Elements = new List<Models.Search.Element>();
        }

        public Result(string xmlPath)
        {
            this.Load(xmlPath);

            Elements = new List<Models.Search.Element>();

            foreach (System.Xml.XmlElement element in this.GetElementsByTagName("Element"))
            {
                Elements.Add(new Models.Search.Element(element));
            }
        }

        public override void Save(string path)
        {
            this.AppendChild(this.CreateXmlDeclaration("1.0", "UTF-8", "yes"));

            this.root = this.CreateElement("SearchResult");

            Elements.ForEach(element =>
            {
                root.AppendChild(element.AppendTo(this));
            });

            this.AppendChild(root);

            base.Save(path);
        }
    }
}
