package com.p3.bewoplaner.data.api.common;

import com.p3.bewoplaner.data.events.InvalidTokenEvent;
import com.p3.bewoplaner.model.common.BaseResponse;

import org.greenrobot.eventbus.EventBus;

import rx.Observable;
import rx.functions.Func1;

/**
 * Created by laszloffiferenc on 2/21/17.
 */
public class ErrorHandlingResponseConverter<T extends BaseResponse>
        implements Func1<T, Observable<T>> {

    @Override
    public Observable<T> call(T t) {
        if (!t.success) {
            if (t.errors.token != null) {
                EventBus.getDefault().post(new InvalidTokenEvent());
                return Observable.error(new ErrorThrowable(ErrorType.INVALID_TOKEN, t.errors));
            }
            return Observable.error(new ErrorThrowable(ErrorType.DATA_INPUT, t.errors));
        }
        return Observable.just(t);
    }
}