package com.cheng.blzb.ui.activity

import android.content.Context
import android.content.Intent
import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import android.os.Bundle
import android.view.Gravity
import android.view.View
import android.view.ViewGroup
import android.widget.FrameLayout
import androidx.core.os.bundleOf
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentContainerView
import com.example.base.extensions.onClick
import com.example.base.ui.BaseActivity
import com.example.base.utils.ScreenUtils
import org.jetbrains.anko.find


/**
 * 仿抽屉activity
 */
class DrawerActivity : BaseActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        val containerView = find<FragmentContainerView>(com.example.base.R.id.fcvContainer)
        val lp = containerView.layoutParams as FrameLayout.LayoutParams
        lp.width = (ScreenUtils.getWindowSize().x * 0.75).toInt()
        lp.height = ViewGroup.LayoutParams.MATCH_PARENT
        lp.gravity = Gravity.END
        containerView.layoutParams = lp

        window.decorView.find<View>(android.R.id.content).onClick { finish() }
    }

    override fun onResume() {
        window.setBackgroundDrawable(ColorDrawable(Color.parseColor("#80000000")))
        super.onResume()
    }

    override fun onPause() {
        window.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))
        super.onPause()
    }

    override fun getFragment(): Fragment {
        val className = intent.getStringExtra(FRAGMENT_CLASS_NAME)!!
        val clazz = Class.forName(className)

        val fragment = clazz.getDeclaredConstructor().newInstance() as Fragment
        fragment.arguments = intent.extras
        return fragment
    }

    companion object {
        const val FRAGMENT_CLASS_NAME = "fragment_class_name"

        fun start(context: Context?, clazz: Class<out Fragment>, vararg args: Pair<String, *>) {
            val intent = Intent(context, DrawerActivity::class.java)
            intent.putExtra(FRAGMENT_CLASS_NAME, clazz.name)
            intent.putExtras(bundleOf(*args))

            context?.startActivity(intent)
        }

        fun newStart(context: Context?, clazz: Class<out Fragment>, vararg args: Pair<String, *>) {
            val intent = Intent(context, DrawerActivity::class.java)
            intent.putExtra(FRAGMENT_CLASS_NAME, clazz.name)
            intent.putExtras(bundleOf(*args))
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
            context?.startActivity(intent)
        }
    }

}
