package com.ydl.component

import android.Manifest
import android.annotation.SuppressLint
import android.content.Intent
import android.net.Uri
import android.provider.Settings
import com.alibaba.android.arouter.launcher.ARouter
import com.tbruyelle.rxpermissions2.RxPermissions
import com.ydl.component.mvp.DemoContract
import com.ydl.component.mvp.DemoPresenter
import com.ydl.ydlcommon.mvp.lce.BaseLceActivity
import com.yidianling.common.tools.ToastUtil
import com.yidianling.consultant.ExpertSearchActivity.Companion.HOT_SEARCH_DOCTOR_NAME
import kotlinx.android.synthetic.main.activity_main.*

/**
 * Created by haorui on 2019-09-01 .
 * Des:
 */
class MainActivity : BaseLceActivity<DemoContract.View, DemoContract.Presenter>(), DemoContract.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() {
        loadData()
        requestPermission()
        tv_user.setOnClickListener {
            loadData()
        }

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

    override fun loadData() {
        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()
                }
            }

    }
}
