package jp.sourceforge.nicoro;

import static jp.sourceforge.nicoro.Log.LOG_TAG;

import android.os.Handler;
import android.os.Looper;
import android.os.Message;

import java.lang.ref.WeakReference;

/**
 * 本体クラスへの参照を{@link WeakReference}で持つ{@link Handler}
 */
public class HandlerWrapper extends Handler {
    private static final boolean DEBUG_LOGD = Release.IS_DEBUG & true;

    private WeakReference<Callback> mCallback;

    public HandlerWrapper(Callback cb) {
        mCallback = new WeakReference<Callback>(cb);
    }
    public HandlerWrapper(Callback cb, Looper looper) {
        super(looper);
        mCallback = new WeakReference<Callback>(cb);
    }

    @Override
    public void handleMessage(Message msg) {
        Callback cb = mCallback.get();
        if (cb == null) {
            if (DEBUG_LOGD) {
                Log.d(LOG_TAG, Log.buf().append("Callback was destroyed or released. ignore message=")
                        .append(msg.toString()).toString());
            }
            return;
        }

        cb.handleMessage(msg);
    }

    /**
     * 明示的に本体クラスとのリンクを解除する
     */
    public void release() {
        Callback cb = mCallback.get();
        if (cb != null) {
            mCallback = new WeakReference<Callback>(null);
        }
    }
}
