package com.za.net

import android.net.ParseException
import com.blankj.utilcode.util.ActivityUtils
import com.blankj.utilcode.util.ThreadUtils
import com.blankj.utilcode.util.ToastUtils
import com.google.gson.JsonParseException
import com.za.base.Const
import com.za.base.view.NetWarnBean
import com.za.base.view.warnBean
import com.za.bean.BaseResponse
import com.za.common.GlobalData
import com.za.common.log.LogUtil
import com.za.service.location.ZdLocationManager
import io.reactivex.rxjava3.core.Observer
import io.reactivex.rxjava3.disposables.Disposable
import org.json.JSONException
import java.net.ConnectException
import java.net.SocketTimeoutException
import java.net.UnknownHostException
import java.util.concurrent.TimeoutException
import javax.net.ssl.SSLHandshakeException

/**
 * Created by DoggieX on 2017/7/26.
 */
abstract class BaseObserver<T> : Observer<BaseResponse<T>> {
	override fun onSubscribe(d : Disposable) { //        if (!NetworkUtils.isAvailable()) {
		//            doFailure(999, "网络无法使用")
		//            d.dispose()
		//        }
	}

	override fun onNext(tBaseResponse : BaseResponse<T>) {
		if (tBaseResponse.isOk) {
			doSuccess(tBaseResponse.result)
			ThreadUtils.runOnUiThread {
				if (warnBean.value != null && warnBean.value is NetWarnBean) {
					warnBean.value = null
				}
			}
		} else {
			when (tBaseResponse.code) {
				3, 401 -> handlerTokenExpired()
			}
			val errMsg = if (null != tBaseResponse.msg) {
				tBaseResponse.msg
			} else if (null != tBaseResponse.message) {
				tBaseResponse.message
			} else {
				"error"
			}
			doFailure(tBaseResponse.code, errMsg)
			if (errMsg?.contains("请下载新版本app!") == true) {
				handlerTokenExpired()
			}
		}
	}

	override fun onError(e : Throwable) {
		LogUtil.print("net error", e)
		when (e) {
			is JsonParseException -> {
				doFailure(1, "数据解析错误")
			}

			is JSONException -> {
				doFailure(1, "数据解析错误")
			}

			is ParseException -> {
				doFailure(1, "数据解析错误")
			}

			is ConnectException -> {
				doFailure(Const.NetWorkException, "与服务器断开连接")
				handlerNetError()
			}

			is UnknownHostException -> {
				doFailure(Const.NetWorkException, "与服务器断开连接")
				handlerNetError()
			}

			is SSLHandshakeException -> {
				doFailure(1, "证书验证失败")
				LogUtil.print("SSLHandshakeException", e)
				handlerNetError()
			}

			is TimeoutException -> {
				doFailure(Const.NetWorkException, "网络连接超时1")
				LogUtil.print("TimeoutException", e)
			}

			is SocketTimeoutException -> {
				doFailure(Const.NetWorkException, "网络连接超时2")
				LogUtil.print("SocketTimeoutException2", e)
				handlerNetError()
			}

			else -> {
				doFailure(1, "error:" + e.message)
				LogUtil.print("other error", e)
			}
		}
	}

	override fun onComplete() {
	}

	abstract fun doSuccess(it : T?)

	abstract fun doFailure(code : Int, msg : String?)

	private fun handlerNetError() {
		ThreadUtils.runOnUiThread {
			if (warnBean.value == null) {
				warnBean.value = NetWarnBean("当前网络异常")
			}
		}

	}

	private fun handlerTokenExpired() {
		ThreadUtils.runOnUiThread {
			try {
				ToastUtils.showShort("登陆信息已过期，请重新登录")
				ZdLocationManager.stopContinuousLocation()
				GlobalData.clearUserCache()
				ActivityUtils.startLauncherActivity()
			} catch (e : Exception) {
				LogUtil.print("handlerTokenExpired", e)
			}
		}
	}
}
