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.launcher.ARouter
import com.tbruyelle.rxpermissions2.RxPermissions
import com.umeng.analytics.MobclickAgent
import com.ydl.component.music.MusicPlayActivity
import com.ydl.component.mvp.DemoContract
import com.ydl.component.mvp.DemoPresenter
import com.ydl.confide.home.ConfideHomeActivity
import com.ydl.media.audio.PlayService
import com.ydl.ydl_router.manager.YDLRouterManager
import com.ydl.ydl_router.manager.YDLRouterParams
import com.ydl.ydlcommon.modular.ModularServiceManager
import com.ydl.ydlcommon.mvp.lce.BaseLceActivity
import com.ydl.ydlcommon.router.IYDLRouterConstant
import com.yidianling.common.tools.ToastUtil
import com.yidianling.consultant.ExpertSearchActivity.Companion.HOT_SEARCH_DOCTOR_NAME
import com.yidianling.consultant.api.IConsultantService
import com.yidianling.fm.api.service.IFMService
import com.yidianling.tests.home.TestHomeActivity
import kotlinx.android.synthetic.main.activity_main.*

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

    private var serviceConnection: ServiceConnection? = null
    protected var playService: PlayService? = 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() {
        bindService()
        reLoadData()
        requestPermission()
        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()
        }
        bt_to_consultant.setOnClickListener {
            ARouter.getInstance()
                .build("/consult/hot_search")
                .withString(
                    HOT_SEARCH_DOCTOR_NAME,
                    this.resources?.getString(R.string.platform_search_hint)
                )
                .navigation()
        }
        bt_to_music.setOnClickListener {
            startActivity(Intent(this, MusicPlayActivity::class.java))
        }
        bt_to_tests.setOnClickListener {
            startActivity(Intent(this, TestHomeActivity::class.java))
        }
        bt_to_confide.setOnClickListener {
            startActivity(Intent(this, ConfideHomeActivity::class.java))
        }
        bt_to_muse.setOnClickListener {
            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()
        }
    }


    override fun reLoadData() {
        mPresenter?.loadUsers()
    }


    @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)
    }

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

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

    override fun onPause() {
        super.onPause()

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


    override fun onDestroy() {
        if (serviceConnection != null) {
            unbindService(serviceConnection)
        }
        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")
        }
    }

}
