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 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?) {
        //恢复置空
        multiScreenService = null
    }
}

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

fun Context.closeAuxiliaryPresentation(){
    if (multiScreenService != null) {
        multiScreenService?.dismissSecondPresentation()
        unbindService(serviceConnection)
    }
}

fun feedData(data: ByteArray){
    multiScreenService?.feedNv21Data(data)
}

