package cn.dankal.basiclib.base.mvp;

import android.util.Log;

import java.lang.ref.WeakReference;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

import cn.dankal.basiclib.util.Logger;

/**
 * description: Presenter 基类
 *
 * @author vane
 * @since 2018/2/1
 */

public abstract class BasePresenter<T extends BaseView> {
    private T mProxyView;

    private WeakReference<T> weakReference;

    public BasePresenter() {

    }

    public void attachView(T view) {
        weakReference = new WeakReference<>(view);

        this.mProxyView = (T) Proxy.newProxyInstance(view.getClass().getClassLoader(), view.getClass().getInterfaces().length<=0?view.getClass().getSuperclass().getInterfaces():view.getClass().getInterfaces(), new MvpInvocationHandler(weakReference.get()));
    }

    public void detachView() {
        if (weakReference != null) {
            if (weakReference.get() != null) {
                weakReference.clear();
            }
            weakReference = null;
        }
    }

    public T getProxyView() {
        return mProxyView;
    }

    private class MvpInvocationHandler implements InvocationHandler {


        private T view;

        public MvpInvocationHandler(T view) {
            this.view = view;
        }

        @Override
        public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
            //如果V层没被销毁, 执行V层的方法.
            if (weakReference != null && weakReference.get() != null) {
                return method.invoke(view, args);
            }
            return null;
        }
    }

}
