package org.qfox.jestful.rxandroid;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

import org.qfox.jestful.client.Client;
import org.qfox.jestful.client.exception.UncertainBodyTypeException;
import org.qfox.jestful.client.scheduler.Scheduler;
import org.qfox.jestful.core.Action;
import org.qfox.jestful.core.Result;

import rx.Observable;
import rx.Subscriber;
import rx.Observable.OnSubscribe;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * <p>
 * Description:
 * </p>
 * 
 * <p>
 * Company: 广州市俏狐信息科技有限公司
 * </p>
 * 
 * @author Payne 646742615@qq.com
 *
 * @date 2016年6月3日 上午11:17:18
 *
 * @since 1.0.0
 */
public class RxAndroidScheduler implements Scheduler {
	
	public boolean supports(Action action) {
		Result result = action.getResult();
		Class<?> klass = result.getKlass();
		return klass == Observable.class;
	}

	public Type getBodyType(Client client, Action action) throws UncertainBodyTypeException {
		Result result = action.getResult();
		Type type = result.getType();
		if (type instanceof ParameterizedType) {
			ParameterizedType parameterizedType = (ParameterizedType) type;
			Type actualTypeArgument = parameterizedType.getActualTypeArguments()[0];
			return actualTypeArgument;
		} else {
			throw new UncertainBodyTypeException(client, action);
		}
	}

	public Object schedule(final Client client, final Action action) throws Exception {
		Observable<Object> observable = Observable.create(new OnSubscribe<Object>() {

			public void call(Subscriber<? super Object> subscriber) {
				try {
					Object value = action.execute();
					subscriber.onNext(value);
				} catch (Throwable e) {
					subscriber.onError(e);
				} finally {
					subscriber.onCompleted();
				}
			}

		});
		return observable.observeOn(Schedulers.io()).subscribeOn(AndroidSchedulers.mainThread());
	}

}

@@ -367,30 +367,8 @@
 le;%0A
-import rx.Subscriber;%0A
 impo
@@ -477,16 +477,38 @@
 edulers;
+%0Aimport rx.Subscriber;
 %0A%0A/**%0A *
@@ -730,17 +730,16 @@
 duler %7B%0A
-%09
 %0A%09public
@@ -1789,22 +1789,24 @@
 ervable.
-observ
+subscrib
 eOn(Sche
@@ -1818,24 +1818,22 @@
 s.io()).
-subscrib
+observ
 eOn(Andr

Remove RxAndroidScheduler's subscribeOn and observeOn