package info.izumin.android.bletia;

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

import org.jdeferred.Promise;

import info.izumin.android.bletia.action.Action;
import info.izumin.android.bletia.wrapper.BluetoothGattWrapper;

/**
 * Created by izumin on 9/14/15.
 */
public class BleMessageThread extends Handler {

    private static final int DELAY_MILLIS = 10;

    private final HandlerThread mHandlerThread;
    private final BluetoothGattWrapper mGattWrapper;
    private final BleActionStore mActionStore;

    public BleMessageThread(HandlerThread handlerThread, BluetoothGattWrapper gattWrapper, BleActionStore actionStore) {
        super(handlerThread.getLooper());
        mHandlerThread = handlerThread;
        mGattWrapper = gattWrapper;
        mActionStore = actionStore;
    }

    public void stop() {
        mHandlerThread.quitSafely();
    }

    public <T> Promise<T, BletiaException, Object> execute(Action<T> action) {
        mActionStore.enqueue(action);
        dispatchMessage(action.obtainMessage());

        return action.getDeferred().promise();
    }

    @Override
    public void handleMessage(Message msg) {
        Action.Type type = Action.Type.valueOf(msg.what);

        if (mActionStore.isRunning(type)) {
            Message delayed = obtainMessage();
            delayed.copyFrom(msg);
            sendMessageDelayed(delayed, DELAY_MILLIS);
        } else {
            mActionStore.execute(type, mGattWrapper);
        }
    }
}

@@ -145,24 +145,48 @@
 d.Promise;%0A%0A
+import java.util.UUID;%0A%0A
 import info.
@@ -222,16 +222,408 @@
 Action;%0A
+import info.izumin.android.bletia.action.EnableNotificationAction;%0Aimport info.izumin.android.bletia.action.ReadCharacteristicAction;%0Aimport info.izumin.android.bletia.action.ReadDescriptorAction;%0Aimport info.izumin.android.bletia.action.ReadRemoteRssiAction;%0Aimport info.izumin.android.bletia.action.WriteCharacteristicAction;%0Aimport info.izumin.android.bletia.action.WriteDescriptorAction;%0A
 import i
@@ -941,35 +941,44 @@
 nal 
-Ble
 Action
-Store mActionStore
+QueueContainer mQueueContainer
 ;%0A%0A 
@@ -1071,34 +1071,43 @@
 er, 
-Ble
 Action
-Store actionStore
+QueueContainer queueContainer
 ) %7B%0A
@@ -1237,33 +1237,39 @@
    m
-ActionStore = actionStore
+QueueContainer = queueContainer
 ;%0A  
@@ -1409,16 +1409,19 @@
 Action%3CT
+, ?
 %3E action
@@ -1436,35 +1436,86 @@
     
-m
 Action
-Store.enqueue(action
+MessageHandler.valueOf(action.getType()).enqueue(action, mQueueContainer
 );%0A 
@@ -1688,98 +1688,94 @@
     
+if (!
 Action
-.Type type = Action.Type.valueOf(msg.what);%0A%0A        if (mActionStore.isRunning(ty
+MessageHandler.valueOf(msg.what).execute(msg, mQueueContainer, mGattWrap
 pe
+r
 )) %7B
@@ -1916,79 +1916,8 @@
 S);%0A
-        %7D else %7B%0A            mActionStore.execute(type, mGattWrapper);%0A
     

Replace BleActionStore with ActionQueueContainer on BleMessageThread