package com.bc_chat.account.presenter

import android.arch.lifecycle.LifecycleOwner
import com.alibaba.android.arouter.launcher.ARouter
import com.bc_chat.account.contract.RegisterContract
import com.bc_chat.account.task.RegisterTask
import com.bc_chat.bc_base.ImService.ImRongService
import com.bc_chat.bc_base.presenter.UpLoadPicturePresenter
import com.bc_chat.bc_base.presenter.WebPresenter
import com.bc_chat.bc_base.utils.Const
import com.google.gson.JsonObject
import com.zhaohaoting.framework.requset.NetWorkCallBack
import com.zhaohaoting.framework.utils.observer.Observer

/**
 * author：Created by zhaohaoting on 2019/3/5
 * email：526309416@qq.com
 * desc：
 */
class RegisterPresenter constructor(view: RegisterContract.View) : UpLoadPicturePresenter<RegisterContract.View>(view), RegisterContract.Presenter {

    private var webPresenter: WebPresenter<RegisterContract.View>? = null

    init {
        webPresenter = WebPresenter(view)
    }

    override fun onCreate(owner: LifecycleOwner?) {
        super.onCreate(owner)
        owner?.lifecycle?.addObserver(webPresenter!!)
    }

    override fun loadWebPage(type: Int) {
        webPresenter?.loadWebPage(type)
    }

    override fun register(phone: String, pwd: String, photo: String?, nickname: String?, introduction: String?, province: String?, city: String?) {
        taskHelper.execute<Any>(RegisterTask(phone, pwd, photo, nickname, introduction, province, city), object : NetWorkCallBack<JsonObject>() {

            override fun onPreExecute(task: Any?) {
                view.showLoading(task)
            }

            override fun onPostExecuteSuccess(task: Any?, data: JsonObject?) {
                val uid = data?.get("uid")?.asString
                val token = data?.get("token")?.asString
                loginIM(uid, token)
            }

            override fun onPostExecuteFailure(task: Any?, exception: Exception?) {
                super.onPostExecuteFailure(task, exception)
                view.registerFailure(exception)
                view.dismissLoading(task)
            }
        })
    }

    /**
     * 登录融云
     */
    private fun loginIM(uid: String?, token: String?) {
        ARouter.getInstance().navigation(ImRongService::class.java).loginIM(uid, token, Observer { key, var1 ->
            if (key.equals(Const.ObserverKey.USER_LOGIN)) {
                if (var1) {
                    view.registerSuccess(uid)
                } else {
                    view.registerFailure(java.lang.Exception("无法连接聊天服务器"))
                }
            }
        })
    }
}
