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

namespace nft.framework.plugin {
    /// <summary>
    /// Instantiate a Contribution class by custom method (maybe according to the description of XML element)
    /// The Contribution should be an instance of specified baseType.
    /// <seealso cref="CustomContributionFactory"/>
    /// </summary>
    [PrimitiveContribution]
    public sealed class CtbAnonymousCtbFactory : Contribution, IContributionFactory {
        public CtbAnonymousCtbFactory(Plugin p, ParamsReader e)
            : base(p, e) {
        }

        #region IContributionFactory メンバ
        public Type OutputType { get { return typeof(CtbAnonymous); } }

        public Contribution load(Plugin owner, ParamsReader reader) {
            Type required = OutputType;
            Type t = PluginUtil.loadTypeFromManifest(reader["class"]);
            if (!t.IsSubclassOf(required))
            {
                string templ = Main.resources["xml.class_cast_error"].stringValue;
                object[] a2 = new object[] { t.FullName, required.Name, reader.SourceURI };
                throw new InvalidCastException(string.Format(templ, a2));
            }
            CtbAnonymous result = null;
            try
            {
                // give XmlNode as first argument of constructor.
                result = Activator.CreateInstance(t, new object[] { reader }) as CtbAnonymous;
            }
            catch (Exception e)
            {
                Debug.WriteLine(e.Message);
                Debug.WriteLine(e.StackTrace);
                string templ = Main.resources["xml.class_load_error"].stringValue;
                throw new Exception(string.Format(templ, t.FullName, reader.SourceURI), e);
            }
            return result;
        }
        #endregion
    }

    public class CtbAnonymous : Contribution {
        public CtbAnonymous(Plugin owner, ParamsReader contrib)
            : base(owner, contrib)
        { 
        }
    }
}
