package com.intergration.avm.utils

import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.ServiceConnection
import android.os.IBinder
import android.text.style.LineHeightSpan
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.SPUtils
import com.intergration.avm.presentation.MultiScreenService
import java.nio.ByteBuffer

const val IMAGE_WIDTH = 1280
const val IMAGE_HEIGHT = 720

fun ByteArray.toByteBuffer():ByteBuffer{
    val buffer = ByteBuffer.allocateDirect(size).also {
        it.put(this)
    }
    buffer.flip()
    return buffer
}

val spUtils: SPUtils by lazy {
    SPUtils.getInstance("avm_settings")
}

const val IS_ACTIVATED = "is_activated"
const val CALIB_RESULT = "calib_result"
const val LOOKUP_TABLE = "lookup_table"

private var multiScreenService: MultiScreenService? = null

private val serviceConnection: ServiceConnection = object : ServiceConnection {
    override fun onServiceConnected(name: ComponentName?, service: IBinder) {
        LogUtils.d("启动副屏服务...")
        multiScreenService = (service as MultiScreenService.MultiScreenBinder).getService()
        //显示第二块屏幕
        multiScreenService?.showSecondPresentation()
    }

    override fun onServiceDisconnected(name: ComponentName?) {
        LogUtils.d("停止副屏服务...")
        //恢复置空
        multiScreenService = null
    }
}

fun Context.openAuxiliaryPresentation(){
    val intent = Intent(this, MultiScreenService::class.java)
    bindService(intent, serviceConnection, Context.BIND_AUTO_CREATE)
}

fun Context.closeAuxiliaryPresentation(){
    LogUtils.i("解绑副屏服务")
    try {
        multiScreenService?.dismissSecondPresentation()
        unbindService(serviceConnection)
    } catch (e: IllegalArgumentException) {
        LogUtils.e("重复解绑副屏服务.${e.message}")
    }
}

fun feedData(data: ByteArray,width:Int = 0,height:Int = 0){
//    multiScreenService?.setYuvDataSize(width = width,height = height)
    multiScreenService?.feedNv21Data(data)
}

