package jp.sourceforge.nicoro;

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

import java.lang.ref.WeakReference;

public class CallbackMessage<S, E> {
    private WeakReference<Handler> mRefHandler;
    private int mWhatSuccess;
    private int mWhatError;
    
    public CallbackMessage(Handler handler, int whatSuccess) {
        mRefHandler = new WeakReference<Handler>(handler);
        mWhatSuccess = whatSuccess;
    }
    public CallbackMessage(Handler handler, int whatSuccess, int whatError) {
        this(handler, whatSuccess);
        mWhatError = whatError;
    }

    public Message obtainMessageSuccess(S obj) {
        Handler handler = mRefHandler.get();
        if (handler == null) {
            return null;
        }
        return handler.obtainMessage(mWhatSuccess, obj);
    }
    public Message obtainMessageError(E obj) {
        Handler handler = mRefHandler.get();
        if (handler == null) {
            return null;
        }
        return handler.obtainMessage(mWhatError, obj);
    }
    
    public boolean sendMessageSuccess(S obj) {
        Message msg = obtainMessageSuccess(obj);
        if (msg == null) {
            return false;
        }
        msg.sendToTarget();
        return true;
    }
    public boolean sendMessageError(E obj) {
        Message msg = obtainMessageError(obj);
        if (msg == null) {
            return false;
        }
        msg.sendToTarget();
        return true;
    }
}
