using System;
using System.Dynamic;
using System.Reflection;

namespace Azyobuzi.Twirunrun
{
    public class DynamicScriptObject : DynamicObject
    {
        private object obj;

        public DynamicScriptObject(object obj)
        {
            this.obj = obj;
        }
        
        public override bool TryGetMember(GetMemberBinder binder, out object result)
        {
            try
            {
                result = obj.GetType().InvokeMember(binder.Name, BindingFlags.GetProperty, null, obj, null);
                return true;
            }
            catch(MissingMemberException)
            {
                result = null;
                return false;
            }
        }

        public override bool TrySetMember(SetMemberBinder binder, object value)
        {
            try
            {
                obj.GetType().InvokeMember(binder.Name, BindingFlags.SetProperty, null, obj, value.ToObjectArray());
                return true;
            }
            catch (MissingMemberException)
            {
                return false;
            }
        }

        public override bool TryInvokeMember(InvokeMemberBinder binder, object[] args, out object result)
        {
            try
            {
                result = obj.GetType().InvokeMember(binder.Name, BindingFlags.InvokeMethod, null, obj, args);
                return true;
            }
            catch (MissingMemberException)
            {
                result = null;
                return false;
            }
        }

        public object GetInnerObject()
        {
            return obj;
        }
    }
}
