package com.yidianling.user.rxlogin

import android.app.Activity
import android.os.Looper
import com.umeng.socialize.UMAuthListener
import com.umeng.socialize.UMShareAPI
import com.umeng.socialize.bean.SHARE_MEDIA
import com.ydl.ydlcommon.data.http.CustomThrowable
import com.yidianling.user.http.request.ThirdLoginParam
import io.reactivex.Observable
import io.reactivex.Observer
import io.reactivex.android.MainThreadDisposable



/**
 * author : Zhangwenchao
 * e-mail : zhangwch@yidianling.com
 * time   : 2018/05/09
 */
class LoginObservable(val activity: Activity, private val media: SHARE_MEDIA): Observable<ThirdLoginParam>() {

    override fun subscribeActual(observer: Observer<in ThirdLoginParam>?) {
        if (!checkMainThread(observer)) {
            return
        }
        val listener = Listener(observer)
        observer?.onSubscribe(listener)
        UMShareAPI.get(activity).deleteOauth(activity, media, listener)
        UMShareAPI.get(activity).getPlatformInfo(activity, media, listener)
    }

    private class Listener(private val observer: Observer<in ThirdLoginParam>?): MainThreadDisposable(), UMAuthListener {
        override fun onDispose() {
        }

        override fun onComplete(p0: SHARE_MEDIA?, p1: Int, p2: MutableMap<String, String>?) {
            if (p0 == null || p2 == null) {
                return
            }
            val param = ThirdLoginParam().apply {
                openid = p2["uid"]
                unionid = p2["unionid"]
                nickname = p2["name"]
                headimgurl = p2["iconurl"]
                city = p2["city"]
                sex = when {
                    p2["gender"].equals("男") -> "1"
                    else -> "2"
                }
            }
            when (p0) {
                SHARE_MEDIA.QQ -> {
                    param.apply {
                        login_type = "QQ"
                    }
                }
                SHARE_MEDIA.WEIXIN -> {
                    param.apply {
                        unionid = p2["uid"]
                        login_type = "weixin"
                    }
                }
                else -> { }
            }
            observer?.onNext(param)

        }

        override fun onCancel(p0: SHARE_MEDIA?, p1: Int) {
            observer?.onError(CustomThrowable("已取消授权"))
        }

        override fun onError(p0: SHARE_MEDIA?, p1: Int, p2: Throwable?) {
            observer?.onError(p2?:Throwable("未知异常"))
        }

        override fun onStart(p0: SHARE_MEDIA?) {

        }
    }

    private fun checkMainThread(observer: Observer<*>?): Boolean {
        if (Looper.myLooper() != Looper.getMainLooper()) {
            observer?.onError(IllegalStateException(
                    "Expected to be called on the main thread but was " + Thread.currentThread().name))
            return false
        }
        return true
    }

}