package com.cr.pages

import android.graphics.Color
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.TextView
import com.cr.cruav.R
import com.cr.data.CrUtil
import com.cr.data.DEFAULT_STR
import com.cr.widget.CrEditTextWidget
import dji.sdk.keyvalue.value.common.LocationCoordinate2D
import dji.v5.common.callback.CommonCallbacks
import dji.v5.common.error.IDJIError
import dji.v5.manager.aircraft.simulator.InitializationSettings
import dji.v5.manager.aircraft.simulator.SimulatorManager
import dji.v5.manager.aircraft.simulator.SimulatorState
import dji.v5.manager.aircraft.simulator.SimulatorStatusListener

/**
 * 操作系统：MAC系统
 * 创建者：王成
 * 创建日期：2023/8/15 10:10
 * 描述：大疆模拟器页面
 */
class FragmentSimulator:CrNavigationFragment(), View.OnClickListener {
    private var txtLongitude:CrEditTextWidget?=null  // define: 2023/8/15 初始经度
    private var txtLatitude:CrEditTextWidget?= null // define: 2023/8/15 初始纬度
    private var btnStart: Button?= null // define: 2023/8/15 启动模拟器
    private var btnEnd:Button?= null // define: 2023/8/15 关闭模拟器
    private var txtInfo:TextView?=null // define: 2023/8/15 展示信息
    /**
     * 初始化
     * @param inflater LayoutInflater
     * @param container ViewGroup?
     * @param savedInstanceState Bundle?
     * @return View?
     */
    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        self = this
        mainView = inflater.inflate(R.layout.frag_dji_simulator,null)
        // todo: 2023/8/15 挂载控件
        joinControls()
        return mainView
    }

    /**
     * 覆写挂载控件方法
     */
    override fun joinControls() {
        // todo: 2023/8/15 挂载控件
        mainView?.let {
            txtLongitude = it.findViewById(R.id.txt_longitude)
            txtLatitude = it.findViewById(R.id.txt_latitude)
            txtInfo = it.findViewById(R.id.txt_info)

            // todo: 2023/8/15 更新信息
            updateInfo(null)

            btnStart = it.findViewById(R.id.btn_start)
            btnEnd = it.findViewById(R.id.btn_end)
            // todo: 2023/8/15 挂载监听
            btnStart?.setOnClickListener(this)
            btnEnd?.setOnClickListener(this)

        }
    }

    /**
     * 覆写初始化页面
     */
    override fun initPage() {
        txtLongitude?.setContent("118.714")
        txtLatitude?.setContent("35.226")
    }

    /**
     * 根据状态更新信息
     * @param state SimulatorState
     */
    private fun updateInfo(state:SimulatorState?){
        var stringBuilder = StringBuilder()
        if(state != null){
            stringBuilder.append(String.format("电机是否运转:%s",if(state.areMotorsOn()) "是" else "否")).append("\r\n")
            stringBuilder.append(String.format("是否飞行:%s",if(state.isFlying) "是" else "否")).append("\r\n")
            stringBuilder.append(String.format("俯仰角:%.2f度",state.pitch)).append("\r\n")
            stringBuilder.append(String.format("翻滚角:%.2f度",state.roll)).append("\r\n")
            stringBuilder.append(String.format("方向角:%.2f度",state.yaw)).append("\r\n")
            stringBuilder.append(String.format("经度:%.6f",state.location.longitude)).append("\r\n")
            stringBuilder.append(String.format("纬度:%.6f",state.location.latitude)).append("\r\n")
            txtInfo?.setTextColor(Color.YELLOW)
        }else{
            stringBuilder.append(String.format("电机是否运转:%s", DEFAULT_STR)).append("\r\n")
            stringBuilder.append(String.format("是否飞行:%s", DEFAULT_STR)).append("\r\n")
            stringBuilder.append(String.format("俯仰角:%.2f度",0f)).append("\r\n")
            stringBuilder.append(String.format("翻滚角:%.2f度",0f)).append("\r\n")
            stringBuilder.append(String.format("方向角:%.2f度",0f)).append("\r\n")
            stringBuilder.append(String.format("经度:%.6f",0f)).append("\r\n")
            stringBuilder.append(String.format("纬度:%.6f",0f)).append("\r\n")
            txtInfo?.setTextColor(Color.WHITE)
        }
        txtInfo?.text = stringBuilder.toString()
    }

    /**
     * 生命周期
     * 销毁
     */
    override fun onDestroy() {
        CrUtil.print("模拟器 页面销毁")
        super.onDestroy()
        // todo: 2023/8/15 移除监听
        SimulatorManager.getInstance().removeSimulatorStateListener(simulatorListener)
        SimulatorManager.getInstance().clearAllSimulatorStateListener()
    }

    /**
     * 生命周期
     * 后台到前台
     */
    override fun onResume() {
        super.onResume()
        // todo: 2023/8/15 添加监听
        SimulatorManager.getInstance().addSimulatorStateListener(simulatorListener)
        // todo: 2023/8/15 初始化页面
        initPage()
        CrUtil.print("模拟器 页面进前台")
    }

    /**
     * 生命周期
     * 后台运行
     */
    override fun onStop() {
        super.onStop()
        // todo: 2023/8/15 移除监听
        SimulatorManager.getInstance().removeSimulatorStateListener(simulatorListener)
        SimulatorManager.getInstance().clearAllSimulatorStateListener()
        CrUtil.print("模拟器 页面进入后台")
    }

    /**
     * 视图点击事件监听
     * @param view View
     */
    override fun onClick(view: View?) {
        when(view?.id){
            R.id.btn_start->{
                // todo: 2023/8/15 启动模拟器
                if(SimulatorManager.getInstance().isSimulatorEnabled){
                    showToast("模拟飞行已启动")
                }else{
                    var longitude = txtLongitude?.getContent()?.toDouble()?:0.0
                    var latitude = txtLatitude?.getContent()?.toDouble()?:0.0
                    var location = LocationCoordinate2D(latitude,longitude)
                    var settings = InitializationSettings.createInstance(location,10)
                    SimulatorManager.getInstance().enableSimulator(settings,object:CommonCallbacks.CompletionCallback{
                        // todo: 2023/8/15 成功
                        override fun onSuccess() {
                            showToast("模拟飞行启动")
                        }

                        // todo: 2023/8/15 失败
                        override fun onFailure(error: IDJIError) {
                            CrUtil.print(error.toString())
                            showError("模拟飞行启动失败:${error.description()}")
                        }
                    })
                }
            }
            R.id.btn_end->{
                // todo: 2023/8/15 关闭模拟器
                if(!SimulatorManager.getInstance().isSimulatorEnabled){
                    showWarning("模拟飞行尚未开启")
                }else{
                    SimulatorManager.getInstance().disableSimulator(object:CommonCallbacks.CompletionCallback{
                        // todo: 2023/8/15 成功
                        override fun onSuccess() {
                            showToast("模拟飞行停止")
                            updateInfo(null)
                        }

                        // todo: 2023/8/15 失败
                        override fun onFailure(error: IDJIError) {
                            showError("模拟飞行停止失败:${error.description()}")
                        }
                    })
                }
            }
        }
    }

    /**
     * 模拟器状态 监听
     */
    private val simulatorListener =
        SimulatorStatusListener { state -> updateInfo(state) }
}