package com.channel.ydl_flutter_base.base

import android.content.Context
import android.content.Intent
import android.graphics.PixelFormat
import android.os.Bundle
import android.util.AttributeSet
import android.view.WindowManager
import com.channel.ydl_flutter_base.plugin.YDLCommonPlugin
import io.flutter.app.FlutterActivity
import io.flutter.plugins.GeneratedPluginRegistrant
import io.flutter.view.FlutterView
import org.json.JSONObject

/**
 * flutter 页面基类
 * Created by xj on 2019/9/30.
 */
abstract class BaseFlutterActivity : FlutterActivity() {

    companion object {

        const val ROUTE_PAGE = "route" //路由

        /**
         * 路由传递过来的参数
         */
        const val  ROUTER_PARAMS = "routerParam"
    }

    override fun createFlutterView(context: Context?): FlutterView {
        val matchParent = WindowManager.LayoutParams(-1, -1)
        val nativeView = this.createFlutterNativeView()
        val flutterView = FlutterView(this, null as AttributeSet?, nativeView)
        flutterView.layoutParams = matchParent
        this.setContentView(flutterView)

        //这个action必加，不然无法在flutter端获取route参数值
        intent.action = Intent.ACTION_RUN

        /**
         * 在这边初始化route
         */
        intent.putExtra(ROUTE_PAGE, initialRoute())

        //渲染优化（优化一丢丢几乎看不出来）
        flutterView.setZOrderOnTop(true)
        flutterView.holder.setFormat(PixelFormat.TRANSLUCENT)

        return flutterView
    }

    public override fun onCreate( savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        GeneratedPluginRegistrant.registerWith(this)

        /**
         * 获取统一路由传递过来的参数并初始化交互通道
         */
        val json = intent.getStringExtra(ROUTER_PARAMS)
        var jb = JSONObject()
        if (json!=null){
            jb = JSONObject(json)
        }
        YDLCommonPlugin.activityRegister(this)
        initChannelPlugin(jb)
    }

    /**
     * 路由，例 "/native/muse/home"
     */
    abstract fun initialRoute(): String

    /**
     * 初始化flutter channel插件
     */
    abstract fun initChannelPlugin(jsonObject: JSONObject)
}