package com.dafay.demo.aidl

import com.dafay.demo.aidl.databinding.ActivityMainBinding
import com.dafay.demo.aidl.inter.ReceiveListener
import com.dafay.demo.aidl.proxy.TestServiceProxy
import com.dafay.demo.lib.base.utils.debug
import com.dafay.demo.lib.base.utils.error
import com.example.demo.lab.base.base.BaseActivity

class MainActivity : BaseActivity<ActivityMainBinding>(ActivityMainBinding::inflate) {

    private val receiveListener = object : ReceiveListener {
        override fun onReceive(msg: String) {
            debug("onReceive:${msg}")
        }
    }

    override fun bindListener() {
        binding.btnBind.setOnClickListener {
            TestServiceProxy.bindService()
        }
        binding.btnRegister.setOnClickListener {
            TestServiceProxy.registerReceiverListener(receiveListener)
        }
        binding.btnAdd.setOnClickListener {
            kotlin.runCatching {
                TestServiceProxy.add(5)
                debug("add end")
            }.let {
                if (it.isFailure) error(it.toString())
            }
        }
        binding.btnCreash.setOnClickListener {
            throw NullPointerException()
        }
        binding.btnTestSyncBind.setOnClickListener {
            for (i in 0 until 3) {
                Thread {
                    TestServiceProxy.bindToService()
                }.start()
            }
        }
        binding.btnTestNums.setOnClickListener {
            for (i in 0 until 1000) {
                TestServiceProxy.add(5)
            }
        }
        binding.btnTestConcurrent.setOnClickListener {
            for (i in 0 until 100) {
                Thread {
                    TestServiceProxy.add(5)
                }.start()
            }
        }
        binding.btnTestMax.setOnClickListener {
            TestServiceProxy.send(generateString(520146))
            // 异常，接近推算值，实际限制推测不是 92
            TestServiceProxy.send(generateString(520148))
        }
        binding.btnTest.setOnClickListener {
            test()
        }
    }

    /**
     *  1MB 减去 8KB（即 1024KB - 8KB），binder 这个限制是二进制数据的长度限制
     *  1 一个字符 2B ？
     *  通过日志测算一下 字符串 到 二进制 的转换
     *  测试 1024*170=174080   348252
     *  测试 1024*180=184320   368732
     *  计算出来 92 + (string.length*2)
     *  推算能传输的最大 String 长度为 (1024*1024-8*1024-92)/2 =520146
     */
    private fun generateString(length: Int): String {
        val charArray = CharArray(length)
        for (i in 0 until length) {
            charArray[i] = if (i % 2 == 0) 'a' else 'b'
        }
        return String(charArray)
    }

    private fun test() {

    }
}