using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;
using VIZ.Framework.Core;

namespace VIZ.Package.Storage
{
    /// <summary>
    /// 控制对象实体节点
    /// </summary>
    public class ControlObject_Entry_Node : IXmlSerialize
    {
        /// <summary>
        /// 名称
        /// </summary>
        public string Name { get; set; }

        /// <summary>
        /// 值
        /// </summary>
        public string Value { get; set; }

        /// <summary>
        /// 子项集合
        /// </summary>
        public List<ControlObject_Entry_Node> Entrys { get; set; } = new List<ControlObject_Entry_Node>();

        /// <summary>
        /// 子项元素集合
        /// </summary>
        public List<ControlObject_Element_Node> Elements { get; set; } = new List<ControlObject_Element_Node>();

        /// <summary>
        /// 从XElement节点获取数据
        /// </summary>
        /// <param name="element">XElement节点</param>
        public void FromXmlElement(XElement element)
        {
            this.Name = element.GetAttributeValue<string>("name");

            if (!element.HasElements)
            {
                this.Value = element.Value;
            }

            foreach (var item in element.Elements("entry"))
            {
                ControlObject_Entry_Node entry = new ControlObject_Entry_Node();
                entry.FromXmlElement(item);

                this.Entrys.Add(entry);
            }

            foreach (var item in element.Elements("element"))
            {
                ControlObject_Element_Node el = new ControlObject_Element_Node();
                el.FromXmlElement(item);

                this.Elements.Add(el);
            }
        }

        /// <summary>
        /// 转化为XElement节点
        /// </summary>
        public XElement ToXmlElement()
        {
            XElement entry = new XElement("entry");
            entry.SetAttributeValueIfValueNotNull("name", this.Name);

            if (this.Value != null)
            {
                entry.Value = this.Value;
            }

            foreach (var item in this.Entrys)
            {
                entry.Add(item.ToXmlElement());
            }

            foreach (var item in this.Elements)
            {
                entry.Add(item.ToXmlElement());
            }

            return entry;
        }
    }
}
