package com.ydl.component

import android.Manifest
import android.annotation.SuppressLint
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.ServiceConnection
import android.net.Uri
import android.os.IBinder
import android.provider.Settings
import android.util.Log
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.mobile.auth.gatewayauth.PhoneNumberAuthHelper
import com.tbruyelle.rxpermissions2.RxPermissions
import com.umeng.analytics.MobclickAgent
import com.ydl.audioim.YDLavManager
import com.ydl.component.music.FragmentContainerActivity
import com.ydl.component.mvp.DemoContract
import com.ydl.component.mvp.DemoPresenter
import com.ydl.component.route.PlatformTempCommonRouteImpl
import com.ydl.component.rtc.MDTLoginActivity
import com.ydl.confide.home.ConfideHomeActivity
import com.ydl.media.audio.PlayService
import com.ydl.ydlcommon.modular.ModularServiceManager
import com.ydl.ydlcommon.mvp.lce.BaseLceActivity
import com.ydl.ydlcommon.router.YdlCommonRouterManager
import com.yidianling.common.tools.LogUtil
import com.yidianling.common.tools.ToastUtil
import com.yidianling.consultant.api.IConsultantService
import com.yidianling.fm.api.service.IFMService
import com.yidianling.muse.event.MeditationFloatEvent
import com.yidianling.muse.helper.MediaPlayerManager
import com.yidianling.muse.service.MeditationWindowService
import com.yidianling.tests.home.NewTestHomeActivity
import com.yidianling.user.api.service.IUserService
import com.yidianling.user.ui.collect.CollectSexAndBirthActivity
import com.yidianling.user.ui.login.OneKeyLoginHelp
import com.yidianling.user.widget.SecretDescriptionDialog
import com.yidianling.user.widget.SecretDialog
import com.yidianling.user.widget.SecretDialog.OnSecretDialogListener
import de.greenrobot.event.EventBus
import kotlinx.android.synthetic.main.activity_main.*


/**
 * Created by haorui on 2019-09-01 .
 * Des:
 */
@Route(path = "/main/main")
class MainActivity : BaseLceActivity<DemoContract.View, DemoContract.Presenter>(),
    DemoContract.View {
    private var secretDescriptionDialog: SecretDescriptionDialog? = null
    private var serviceConnection: ServiceConnection? = null

    private var meditationServiceConnection:ServiceConnection? = null

    private var secretDialog: SecretDialog? = null
    protected var playService: PlayService? = null

    protected var meditationService:MeditationWindowService?=null

    override fun getContentViewId(): Int {
        return R.id.lce_content_view
    }

    override fun getStateViewId(): Int {
        return R.id.lce_state_view
    }

    override fun setData(data: String) {
        tv_content.text = data
    }

    override fun createPresenter(): DemoContract.Presenter {
        return DemoPresenter()
    }

    override fun layoutResId(): Int {
        return R.layout.activity_main
    }

    override fun initDataAndEvent() {

        EventBus.getDefault().register(this)
        //线上
//        YDLavManager.instances.init(this, "3387e9b251f3491e9221a9877e8f7830")
        //测试
        YDLavManager.instances.init(this, "13b1536698f64905a1e7e5bb978ba821")

        YdlCommonRouterManager.initYdlCommonRoute(PlatformTempCommonRouteImpl())
        // 初始化一键登录sdk
        OneKeyLoginHelp.sdkInit(this, OneKeyLoginHelp.YDL_USER_APP, PhoneNumberAuthHelper.SERVICE_TYPE_LOGIN)
        bindService()
        bindMeditationService()
        
//        reLoadData()
        requestPermission()
        bt_mdt.setOnClickListener {
            val intent = Intent(this, MDTLoginActivity::class.java)
            startActivity(intent)
        }

        tv_user.setOnClickListener {
            reLoadData()
        }

        tv_home?.setOnClickListener {
            mPresenter.loadHome()
        }

        bt_to_other.setOnClickListener {
//            ARouter.getInstance().build("/user/login")
//                .withBoolean("bind_phone", false)
//                .withBoolean("isFromGuide", true)
//                .navigation()
            OneKeyLoginHelp.startLogin(this,false)
        }
        bt_to_consultant.setOnClickListener {
            //            ARouter.getInstance()
//                .build("/consult/hot_search")
//                .withString(
//                    HOT_SEARCH_DOCTOR_NAME,
//                    this.resources?.getString(R.string.platform_search_hint)
//                )
//                .navigation()
            FragmentContainerActivity.start(this, "ExpertSearchFragment")
        }
        bt_to_music.setOnClickListener {
            FragmentContainerActivity.start(this)
        }
        bt_to_im.setOnClickListener {
            FragmentContainerActivity.start(this, "NewMultiMessageFragment")
        }
        bt_to_dynamic.setOnClickListener {
            FragmentContainerActivity.start(this, "TrendsHomeFragment")
        }
        bt_to_tests.setOnClickListener {
            startActivity(Intent(this, NewTestHomeActivity::class.java))
            //                                SecretActivity.Companion.startProtocol(this, it.data.getContent());
//             secretDescriptionDialog = SecretDescriptionDialog(
//                this@MainActivity,
//               "122342453653456345674356",
//                object : OnSecretDescriptionDialogListener {
//                    override fun onCancel() {
//                        secretDescriptionDialog!!.dismiss()
//                        showEnsureDialog()
//                    }
//
//                    override fun onSure() {
//                        secretDescriptionDialog!!.dismiss()
//                    }
//                })
//            secretDescriptionDialog!!.setCanceledOnTouchOutside(false)
//            secretDescriptionDialog!!.show()

        }
        bt_to_collect_info.setOnClickListener {
            startActivity(Intent(this, CollectSexAndBirthActivity::class.java))
        }
        bt_to_confide.setOnClickListener {
            YDLavManager.instances.login(ModularServiceManager.provide(IUserService::class.java).getUserInfo()?.uid)
            startActivity(Intent(this, ConfideHomeActivity::class.java))
        }

        ModularServiceManager.provide(IConsultantService::class.java).requestGuideData()
        bt_to_muse.setOnClickListener {

            ARouter.getInstance().build("/muse/play")
                .navigation()

            val list =
                ModularServiceManager.provide(IConsultantService::class.java).getGuideImage(1)
            list?.forEach {
                LogUtil.e(it.toString())
            }
            //            YDLRouterManager.router(IYDLRouterConstant.ROUTER_MUSE_CENTER,
//                YDLRouterParams().putExtra
//            ("url", "http://video.yidianling.com/2019/05/30/746851e2f335baf5f44499f4fb49d3a9.mp3"))

//            YDLRouterManager.router(
//                IYDLRouterConstant.ROUTER_MUSE,
//                YDLRouterParams().putExtra(
//                    IYDLRouterConstant.MUSIC_URL,
//                    "http://video.yidianling.com/2019/05/30/e6d4a71e8c895f2156a2ff37d93ca3a9.mp3"
//                )
//                    .putExtra(
//                        IYDLRouterConstant.DATA_JSON, "{\n" +
//                                "        \"muses\": [{\n" +
//                                "        \"id\": 6,\n" +
//                                "        \"name\": \"冥想基础介绍-1-什么是冥想？\",\n" +
//                                "        \"audioUrl\":\n" +
//                                "        \"http://video.yidianling.com/2019/05/30/e6d4a71e8c895f2156a2ff37d93ca3a9.mp3\",\n" +
//                                "        \"backgroundUrl\":\n" +
//                                "        \"https://img.yidianling.com/file/2019/06/10/i4qdax82ok2aizq3.png\",\n" +
//                                "        \"effectCode\": 1,\n" +
//                                "        \"category\": 2,\n" +
//                                "        \"playCount\": 929,\n" +
//                                "        \"sort\": 255,\n" +
//                                "        \"isDelete\": 1,\n" +
//                                "        \"createTime\": \"May 30, 2019 4:45:17 PM\",\n" +
//                                "        \"updateTime\": \"Jun 10, 2019 7:14:23 PM\"\n" +
//                                "    }]\n" +
//                                "    }"
//                    )
//            )
        }

        bt_to_fm.setOnClickListener {
            startActivity(ModularServiceManager.provide(IFMService::class.java).fmListIntent(this))
//            YDLRouterManager.router(IYDLRouterConstant.ROUTER_FM_LIST)
        }

        bt_to_course.setOnClickListener {
            ARouter.getInstance().build("/course/home")
                .navigation()
        }
        bt_to_home.setOnClickListener {
            FragmentContainerActivity.start(this, "YdlHomeFragment")
        }
        bt_to_mine.setOnClickListener {
            FragmentContainerActivity.start(this, "MineFragment")
        }

        bt_to_privacy.setOnClickListener {
            startActivity(Intent(this@MainActivity, TestAppActivity::class.java))
        }

    }


    override fun reLoadData() {
        mPresenter.loadHome()
    }


    @SuppressLint("CheckResult")
    private fun requestPermission() {
        val rxPermissions = RxPermissions(this)
        rxPermissions.requestEach(Manifest.permission.WRITE_EXTERNAL_STORAGE)
            .subscribe { permission ->
                if (permission.granted) {
                    ToastUtil.toastShort("Permission Success")
                } else if (permission.shouldShowRequestPermissionRationale) {
                    requestPermission()
                } else {
                    ToastUtil.toastLong(
                        this,
                        getString(R.string.platform_need_storage_permission_hint)
                    )
                    val intent = Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS)
                    val uri = Uri.fromParts("package", packageName, null)
                    intent.data = uri
                    startActivity(intent)
                    finish()
                }
            }

    }

    private fun bindService() {
        val intent = Intent()
        intent.setClass(this, PlayService::class.java!!)
        serviceConnection = PlayServiceConnection()
        bindService(intent, serviceConnection, Context.BIND_AUTO_CREATE)
    }

    private fun bindMeditationService(){
        val intent = Intent()
        intent.setClass(this,MeditationWindowService::class.java)
        meditationServiceConnection = MeditationServiceConnection()
        bindService(intent,meditationServiceConnection,Context.BIND_AUTO_CREATE)
    }

    override fun onResume() {
        super.onResume()
        MobclickAgent.onResume(this)

//        ModularServiceManager.provide(IConsultantService::class.java)
//            .
//            (this)
    }

    override fun onPause() {
        super.onPause()

//        ModularServiceManager.provide(IConsultantService::class.java).hideConsultAssistantDialog()
    }

    fun onEvent(event:MeditationFloatEvent){
        
    }

    @SuppressLint("MissingSuperCall")
    override fun onDestroy() {
        if (serviceConnection != null) {
            unbindService(serviceConnection)
        }
        if(meditationServiceConnection!=null){
            EventBus.getDefault().post(MeditationFloatEvent(false))
            MediaPlayerManager.getInstance(this)?.stop()
            unbindService(meditationServiceConnection)
        }
        if(EventBus.getDefault().isRegistered(this)){
            EventBus.getDefault().unregister(this)
        }
        super.onDestroy()
    }

    private inner class PlayServiceConnection : ServiceConnection {
        override fun onServiceConnected(name: ComponentName, service: IBinder) {
            playService = (service as PlayService.PlayBinder).service
        }

        override fun onServiceDisconnected(name: ComponentName) {
            Log.e(javaClass.simpleName, "service disconnected")
        }
    }

    private inner class MeditationServiceConnection:ServiceConnection {
        override fun onServiceConnected(name: ComponentName?, service: IBinder?) {
            meditationService = (service as MeditationWindowService.MeditationBinder).service
        }

        override fun onServiceDisconnected(name: ComponentName?) {

        }

    }

    private fun showEnsureDialog() {
        secretDialog = SecretDialog(this, object : OnSecretDialogListener {
            override fun onCancel() {
                secretDialog!!.dismiss()
//                finishAll()
//                Process.killProcess(Process.myPid())
//                System.exit(0)
            }

            override fun onSure() {
                secretDialog!!.dismiss()
            }
        })
        secretDialog!!.setCanceledOnTouchOutside(false)
        secretDialog!!.show()
    }

}
