#region COPYRIGHT
//
//     THIS IS GENERATED BY TEMPLATE
//     
//     AUTHOR  :     ROYE
//     DATE       :     2010
//
//     COPYRIGHT (C) 2010, TIANXIAHOTEL TECHNOLOGIES CO., LTD. ALL RIGHTS RESERVED.
//
#endregion

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

namespace System.Reflection.Emit
{
    internal class CtorInvocationEmitter_ : InvocationEmitter_
    {
        public CtorInvocationEmitter_(CallInfo_ callInfo, DelegateCache cache)
            : base(callInfo, cache)
        {
        }

        protected override object Invoke(Delegate action)
        {
            var invocation = (ConstructorInvoker)action;
            return invocation.Invoke(CallInfo.Parameters);
        }

        protected override Delegate CreateDelegate()
        {
            ConstructorInfo ctorInfo = CallInfo.TargetType.GetConstructor(BindingFlags.ExactBinding | Flags.InstanceAnyVisibility,
                null,
                CallingConventions.HasThis,
                CallInfo.ParamTypes,
                null);
            if (ctorInfo == null)
            {
                throw new MissingMemberException("Constructor does not exist");
            }

            DynamicMethod method = CreateDynamicMethod("ctor", CallInfo.TargetType, Constants.ObjectType, new[] { Constants.ObjectType });
            ILGenerator generator = method.GetILGenerator();

            LoadLocalsFromArguments(generator, 0);
            PushLocalsToStack(generator);
            generator.Emit(OpCodes.Newobj, ctorInfo);
            ReturnValue(generator, CallInfo.TargetType);
            
            return method.CreateDelegate(typeof(ConstructorInvoker));
        }
    }
}
