package tech.starwin.impl;

import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import retrofit2.HttpException;
import tech.starwin.R;
import tech.starwin.LibConfig;
import tech.starwin.network.Error;
import tech.starwin.utils.LoginManager;

/**
 * Created by SiKang on 2018/9/14.
 * HTTP请求回调
 */
public abstract class HttpObserver<T> implements Observer<T> {
    private Disposable disposable;

    public abstract void onStart();

    public abstract void onSuccess(T data);

    public abstract void onError(int code, String msg);

    public abstract void onFinish();


    @Override
    public void onSubscribe(Disposable d) {
        this.disposable = d;
        onStart();
    }

    @Override
    public void onNext(T tResult) {
        onSuccess(tResult);
    }

    @Override
    public void onError(Throwable throwable) {
        onFinish();
        try {
            if (throwable != null) {
                String msg = throwable.getMessage();
                if (isHttpError(msg)) {
                    onError(Error.HTTP_ERROR, LibConfig.getContext().getString(R.string.text_net_error));
                } else if (throwable instanceof HttpException) {
                    if (!isCanHandle((HttpException) throwable)) {
                        onError(Error.SERVER_ERROR, msg);
                    }
                } else if (msg.contains("java.lang.IllegalStateException")) {
                    onError(Error.APP_ERROR, LibConfig.getContext().getString(R.string.text_app_error));
                } else if (msg.contains("body is null")) {
                    onSuccess(null);
                }

            }
        } catch (Throwable e) {
            onError(Error.APP_ERROR, LibConfig.getContext().getString(R.string.text_app_error));
        }
        if (disposable != null)
            disposable.dispose();
    }

    @Override
    public void onComplete() {
        onFinish();
        if (disposable != null)
            disposable.dispose();
    }

    /**
     * 可预处理的错误
     */
    private boolean isCanHandle(HttpException exception) {
        switch (exception.code()) {
            case 401://Token失效
                LoginManager.get().tokenInvalid();
                return true;
            case 403:
                // TODO 短信发送失败
                return true;
            case 409:
                // TODO 版本更新
                return true;
            case 412:
                // TODO 参数缺失
                return true;
        }
        return false;
    }

    /**
     * 链路错误
     */
    private boolean isHttpError(String msg) {
        String[] errorArray = new String[]{
                "timeout",
                "java.net.ConnectException",
                "java.net.SocketTimeoutException",
                "failed",
                "Failed to connect to",
                "stream was reset",
                "Unable to resolve host",
                "SSL handshake time out",
                "time out"
        };
        for (String error : errorArray) {
            if (msg.contains(error))
                return true;
        }
        return false;
    }

}
