package jp.sourceforge.nicoro;

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

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

import java.lang.ref.WeakReference;

/**
 *
 * @param <S> 成功時のMessage.objのクラス
 * @param <E> エラー時のMessage.objのクラス。使用しない場合はVoidにでも設定しておくこと
 */
public class CallbackMessage<S, E> {
    private static final boolean DEBUG_LOGD = Release.IS_DEBUG & true;

    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) {
            if (DEBUG_LOGD) {
                Log.d(LOG_TAG, "CallbackMessage#obtainMessageSuccess: Handler was removed");
            }
            return null;
        }
        return handler.obtainMessage(mWhatSuccess, obj);
    }
    public Message obtainMessageError(E obj) {
        Handler handler = mRefHandler.get();
        if (handler == null) {
            if (DEBUG_LOGD) {
                Log.d(LOG_TAG, "CallbackMessage#obtainMessageError: Handler was removed");
            }
            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;
    }
}
