package io.nexilis.service

import android.util.Log
import io.newuniverse.SDK.nuSDKCallBack
import io.nexilis.service.core.Data
import io.nexilis.service.core.Incoming
import kotlin.concurrent.withLock

class SdkCallback : nuSDKCallBack {

    private val tag = "SdkCallback"

    override fun connectionStateChanged(
        p0: String?,
        p1: String?,
        p2: Boolean,
        p3: Int,
        p4: Int,
        p5: Byte
    ) {
        Log.d(tag, "connectionStateChanged:$p0:$p1:$p2:$p3:$p4:$p5")
        try {
            Api.condition?.let {
                Api.lock.withLock {
                    if (p5 == "1".toByte()) it.signal()
                }
            }
        } catch (e: Exception) {
            Log.e(tag, e.message, e)
        }
    }

    override fun gpsStateChanged(p0: Int) {
        Log.d(tag, "gpsStateChanged:$p0")
    }

    override fun sleepStateChanged(p0: Boolean) {

    }

    override fun callStateChanged(p0: Int, p1: String?): Int {
        return 0
    }

    override fun bcastStateChanged(p0: Int, p1: String?): Int {
        return 0
    }

    override fun sshareStateChanged(p0: Int, p1: String?): Int {
        return 0
    }

    override fun incomingData(p0: String?, p1: Any?) {
        Log.d(tag, "incomingData:$p0:$p1")
        try {
            p1?.let {
                val data = Data()
                when (it) {
                    is String -> {
                        data.parse(it)
                    }
                    is ByteArray -> {
                        data.parse(it)
                    }
                    else -> {
                        Log.d(tag, "unknown:$p0:$p1")
                        return
                    }
                }
                p0?.let { s ->
                    data.packetId = s
                }
                Incoming.getInstance().process(data)
            }
        } catch (e: Exception) {
            Log.e(tag, e.message, e)
        }
    }

    override fun lateResponse(p0: String?, p1: String?) {

    }

    override fun asycnACKReceived(p0: String?) {

    }

    override fun locationUpdated(p0: Long, p1: String?) {
        Log.d(tag, "locationUpdated:$p0:$p1")
    }

    override fun imageData(p0: ByteArray?) {

    }

    override fun initSelfieSegmentation(p0: Int, p1: Int) {

    }

    override fun resetDB() {

    }
}