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 = I18n.T("Cannot cast the class'{0}' to the class'{1}'.");
                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[] { owner, reader }) as CtbAnonymous;
            }
            catch (Exception e)
            {
                Debug.WriteLine(e.Message);
                Debug.WriteLine(e.StackTrace);
                string templ = I18n.T("Failed to create an instance of the class '{0}'.");
                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)
        { 
        }
    }
}
