package cn.thens.kdroid.core.log

class ChunkPrinter(private val printer: LinePrinter) : StoryPrinter {
    override fun print(message: String) {
        if (message.isEmpty()) return
        val bytes = message.toByteArray()
        val length = bytes.size
        val pageSize = (length - 1) / CHUNK_SIZE + 1
        for (i in 0 until pageSize) {
            val offset = i * CHUNK_SIZE
            val count = Math.min(length - offset, CHUNK_SIZE)
            printChunk(String(bytes, offset, count, Charsets.UTF_8))
        }
    }

    private fun printChunk(chunk: String) {
        val lines = chunk.split('\n').dropLastWhile { it.isEmpty() }.toTypedArray()
        for (line in lines) {
            printer.print(line)
        }
    }

    companion object {
        private const val CHUNK_SIZE = 4 * 1024
    }
}