package com.ydl.component.mvp

import com.google.gson.JsonArray
import com.google.gson.JsonObject
import com.ydl.component.model.HomeFMBean
import com.ydl.media.audio.AudioPlayer
import com.ydl.media.audio.model.Music
import com.ydl.ydlcommon.data.http.RxUtils
import com.ydl.ydlcommon.mvp.base.BasePresenter
import com.ydl.ydlnet.client.observer.CommonObserver

/**
 * Created by haorui on 2019-09-01 .
 * Des:
 */
class DemoPresenter : BasePresenter<DemoContract.View,DemoContract.Model>(),
    DemoContract.Presenter {

    override fun loadFmMusic() {
        mModel.getFmMusic()
            .compose(RxUtils.applySchedulers(mView))
            .subscribe(object : CommonObserver<HomeFMBean>() {
                override fun onError(errorMsg: String) {
                }

                override fun onSuccess(homeFMBean: HomeFMBean) {
//                    var jsonStirng = Gson().toJson(homeFMBean.list)
//                    val list = Gson().fromJson<ArrayList<Music>>(jsonStirng, object : TypeToken<ArrayList<Music>>() {}.type)
                    homeFMBean.list?.let {
                        AudioPlayer.get().addPlayList(stringToMusicPlayerList(it))
                        mView.setData("")
                    }
                }
            })

    }

    override fun loadHome() = mModel!!.getHome()
        .compose(RxUtils.applySchedulers(mView))
        .subscribe(object : CommonObserver<JsonObject>() {
            override fun onError(errorMsg: String) {
            }

            override fun onSuccess(users: JsonObject) {
                var cateTitle = users.getAsJsonObject("data").getAsJsonArray("askCategoryData").get(0).asJsonObject.get("cateTitle").asString;
                mView?.setData(cateTitle)
            }
        })

    override fun loadUsers() = mModel!!.getUser()
        .compose(RxUtils.applySchedulers(mView))//使用 Rxlifecycle,使 Disposable 和 Activity 一起销毁
        .subscribe(object : CommonObserver<JsonArray>() {
            override fun onError(errorMsg: String) {
            }

            override fun onSuccess(users: JsonArray) {
                var userName = users.get(0).asJsonObject.get("login").asString
                mView?.setData(userName)
            }
        })

    override fun createModel(): DemoContract.Model {
        return DemoModel()
    }

    //将列表转为播放器可用列表
    private fun stringToMusicPlayerList(list: List<HomeFMBean.ListBean>): ArrayList<Music> {
        var nlist = ArrayList<Music>()
        try {
            for (i in list.indices) {
                var be = Music()
                be.path = list[i].path
                be.coverPath = list[i].coverPath
                be.title = list[i].title
                be.album = list[i].album
                be.artist = list[i].artist
                nlist.add(be)
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return nlist
    }


}
