package com.yidianling.muse.handler

import android.graphics.drawable.Drawable
import com.google.gson.Gson
import com.ydl.media.audio.AudioPlayer
import com.ydl.media.audio.model.Music
import com.ydl.ydlcommon.utils.YDLCacheUtils
import com.ydl.ydlcommon.view.dialog.YDLShareDialog
import com.yidianling.common.tools.ToastUtil
import com.yidianling.muse.R
import com.yidianling.muse.bean.MuseModuleBean
import io.flutter.app.FlutterActivity
import io.flutter.plugin.common.MethodCall
import io.flutter.plugin.common.MethodChannel


/**
 * Created by xj on 2019/9/6.
 */
class MusePlugin : MethodChannel.MethodCallHandler {

    companion object {
        const val CHANNEL: String = "lib/fm_module/channel"

        const val ACTION_GET_APPINFO_INITIAL_DATA = "action_get_initial_app_info_data" //获取主包信息的数据
        const val ACTION_GET_MUSIC_INITIAL_DATA = "action_get_initial_music_data" //获取音乐原生的数据
        const val ACTION_PLAY_MUSIC = "action_play_music" //播放音乐
        const val ACTION_PAUSE_MUSIC = "action_pause_music" //暂停音乐
        const val ACTION_STOP_MUSIC = "action_stop_music" //暂停(销毁)音乐
        const val ACTION_SET_DEFAULT_TIME = "action_set_default_time" //时间控制页面设置时间
        const val ACTION_POP_PAGE = "action_pop_page" //pop当前页面
        const val ACTION_SHARE_WX = "action_share_wx" //分享至微信
        const val ACTION_SET_BGIMG = "action_set_bgImg"; //设置背景图片

        var currentMusicUrl: String = "" //当前正在播放的冥想url
        var data: MuseModuleBean? = null //冥想数据

        fun rigister(activity: FlutterActivity, currentUrl: String?, dataJson: String) {
            currentUrl?.let {
                currentMusicUrl = currentUrl
            }
            data = Gson().fromJson(dataJson, MuseModuleBean::class.java)
            MethodChannel(activity.flutterView, CHANNEL).setMethodCallHandler(MusePlugin(activity))
        }
    }


    private var mActivity: FlutterActivity? = null

    private constructor(activity: FlutterActivity) {
        mActivity = activity
    }

    override fun onMethodCall(methodCall: MethodCall, result: MethodChannel.Result) {
        methodCall?.let {
            when (methodCall.method) {
                // flutter获取原生的音乐数据
                ACTION_GET_MUSIC_INITIAL_DATA -> {
                    val mMap = mutableMapOf<String, Any>()
                    mMap["defaultTime"] = getDefaultTime()
                    mMap["currentMusicUrl"] = currentMusicUrl
                    mMap["dataJson"] = Gson().toJson(data)
                    result?.success(mMap)
                }
                // 播放音乐
                ACTION_PLAY_MUSIC -> {
                    var musicUrl: String? = methodCall.argument<String>("url")
                    var mContinue: Boolean = methodCall.argument<Boolean>("mContinue")!!

                    if (mContinue) {
                        AudioPlayer.get().seekTo(-1, AudioPlayer.get().audioPosition)
                        AudioPlayer.get().startPlayer()
                    }else {
                        val music = Music()
                        music.path = musicUrl ?: currentMusicUrl
                        music.album = ""
                        music.artist = ""
                        music.coverPath = ""
                        music.title = ""
                        AudioPlayer.get().singleCirclePlay(music)
                    }
                }
                // 暂停音乐
                ACTION_PAUSE_MUSIC -> {
                    AudioPlayer.get().pausePlayer()
                }
                // 暂停（销毁）音乐
                ACTION_STOP_MUSIC -> {
                    AudioPlayer.get().stopPlayer()
                }
                // 设置默认时间
                ACTION_SET_DEFAULT_TIME -> {
                    YDLCacheUtils.saveMuseDefaultTime(methodCall.argument<Int>("time").toString())
                }
                // 退出flutteractivity
                ACTION_POP_PAGE -> {
                    mActivity?.finish()
                }
                // 分享
                ACTION_SHARE_WX -> {
                    share(methodCall)
                }
                //设置背景图片
                ACTION_SET_BGIMG -> {
                    var mDrawable: Drawable?
                    when (methodCall.arguments) {
                        "sleeps_icon_default" -> {
                            mDrawable = mActivity?.resources?.getDrawable(R.drawable.muse_sleeps_icon_default)
                        }
                        "sleeps_icon_playing" -> {
                            mDrawable = mActivity?.resources?.getDrawable(R.drawable.muse_sleeps_icon_playing)
                        }
                        "muse_icon_default" -> {
                            mDrawable = mActivity?.resources?.getDrawable(R.drawable.muse_muse_icon_default)
                        }
                        "muse_icon_playing" -> {
                            mDrawable = mActivity?.resources?.getDrawable(R.drawable.muse_muse_icon_playing)
                        }
                        else -> {
                            mDrawable = mActivity?.resources?.getDrawable(R.drawable.muse_sleeps_icon_default)
                        }
                    }
                    mDrawable?.let {
                        mActivity?.window?.setBackgroundDrawable(mDrawable)
                    }
                }
                else -> {
                }
            }
        }
    }

    /**
     * 分享，跟FM一致
     */
    private fun share(methodCall: MethodCall?) {
        var shareUrl = methodCall?.argument<String>("shareUrl")?:""
        var title = methodCall?.argument<String>("title")?:""
        var path = methodCall?.argument<String>("path")?:""
        var appId = methodCall?.argument<String>("appId")?:""
        if (shareUrl.isEmpty()) {
            ToastUtil.toastShort("分享数据获取失败")
        }else {
            val dialog = YDLShareDialog.style7(mActivity!!, title, shareUrl, "壹点零冥想", "https://img.yidianling.com/file/2019/06/10/fm0vovijx0p2br9s.png", path, appId)
            dialog.setCallBack(object : YDLShareDialog.ICallBack {
                override fun callBack(type: Int) {
                }
            })
            dialog.show(mActivity!!.fragmentManager, "lose")
        }
    }

    /**
     * 获取默认时间
     */
    private fun getDefaultTime(): Int {
        var time = YDLCacheUtils.getMuseDefaultTime()
        return try {
            time.toInt()
        } catch (e: Exception) {
            600
        }
    }
}