package de.beyondsoft.ownchat.data.api.common;

import de.beyondsoft.ownchat.data.events.InvalidTokenEvent;
import de.beyondsoft.ownchat.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));
            }

            if(t.errors.chatCodeFailed != null) {
                return Observable.error(new ErrorThrowable(ErrorType.WRONG_CHATCODE, t.errors));
            }

            if(t.errors.chatCodeInactive != null) {
                return Observable.error(new ErrorThrowable(ErrorType.DEACTIVATED_CHATCODE, t.errors));
            }

            if(t.errors.chatCodeTooShort != null) {
                return Observable.error(new ErrorThrowable(ErrorType.CHATCODE_TOO_SHORT, t.errors));
            }

            return Observable.error(new ErrorThrowable(ErrorType.DATA_INPUT, t.errors));
        }

        return Observable.just(t);
    }
}