using System;
using System.Collections.Generic;
using System.Text;
using System.Xml;
using nft.util;

namespace nft.framework.loader
{
    public class XmlParamParser : IParamsParser
    {
        protected XmlNode node;
        public XmlParamParser(XmlNode xnode) {
            this.node = xnode;
        }

        public string InnerText {
            get {
                return node.InnerText;
            }
        }

        public bool IsNull {
            get { return false; }
        }

        public IEnumerator<KeyValuePair<String, IParamsParser>> EnumChildren() {
            foreach (XmlAttribute a in node.Attributes) {
                yield return new KeyValuePair<String,IParamsParser>(a.Name, new PlainStringParam(a.Value, this));
            }
            foreach (XmlNode n in node.ChildNodes) {
                yield return new KeyValuePair<String, IParamsParser>(n.Name, new XmlParamParser(n));
            }
        }

        public IEnumerator<IParamsParser> EnumChildren(string key) {
            if (node.Attributes != null) {
                XmlAttribute a = node.Attributes[key];
                if (a != null) {
                    yield return new PlainStringParam(a.Value, this);
                }
            }
            foreach (XmlNode n in node.SelectNodes(key)) {
                yield return new XmlParamParser(n);
            }
        }

        public IFileSource GetFileSource(string path) {
            if (path != null && path.Length > 0) {
                Uri uri = XmlUtil.resolve(node, path);
                if (uri.IsFile) {
                    return new LocalFile(uri.LocalPath);
                }
            }
            return null;
        }
    }

}
