package com.yidianling.muse.activity

import android.annotation.SuppressLint
import android.text.TextUtils
import com.alibaba.android.arouter.facade.annotation.Route
import com.google.gson.Gson
import com.ydl.ydl_router.manager.YDLRouterManager
import com.ydl.ydl_router.manager.YDLRouterParams
import com.ydl.ydlcommon.base.BaseActivity
import com.ydl.ydlcommon.data.http.RxUtils
import com.ydl.ydlcommon.data.http.ThrowableConsumer
import com.ydl.ydlcommon.router.IYDLRouterConstant
import com.yidianling.home.http.MuseHttp
import io.reactivex.functions.Consumer
import org.json.JSONException
import org.json.JSONObject

/**
 * 冥想跳转中间页面，用于统一路由跳转，在这里获取冥想助眠的列表数据，并解析统一路由的url（该url必须为接口数据中的一个）作为播放url
 */

@Route( path = "/muse/MuseService")
class MuseCenterActivity: BaseActivity() {

    private var currentUrl: String? = null


    override fun initDataAndEvent() {
        supportActionBar?.hide()

        if (intent.hasExtra("routerParam")) {
            val json = intent.getStringExtra("routerParam")
            if (!TextUtils.isEmpty(json)) {
                try {
                    val jsonObject = JSONObject(json)
                    currentUrl = jsonObject.getString("url")
                } catch (e: JSONException) {
                    e.printStackTrace()
                }

            }
        }

        //调用接口获取所有数据
        getData()

    }

    @SuppressLint("CheckResult")
    private fun getData() {
        MuseHttp.getInstance().newMuseRequest()
            .compose(RxUtils.applySchedulers())
            .map { it }
            .filter { true }
            .subscribe(Consumer {
                var dataJson = Gson().toJson(it.data)
                YDLRouterManager.router(
                    IYDLRouterConstant.ROUTER_MUSE,
                    YDLRouterParams().putExtra(IYDLRouterConstant.MUSIC_URL, currentUrl?:"")
                        .putExtra(IYDLRouterConstant.DATA_JSON, dataJson))
                finish()
            }, object : ThrowableConsumer() {
                override fun accept(msg: String) {
                    finish()
                }
            })
    }

    override fun layoutResId(): Int {
        return 0
    }

}