package de.storchp.fdroidbuildstatus.utils

import java.util.stream.Collectors
import java.util.stream.StreamSupport

class LoglinesBuffer(size: Int) : Iterable<String?> {
    private val loglines: Array<String?> = arrayOfNulls(size)
    private var startPos = -1
    private var lastPos = -1

    fun add(line: String?) {
        val nextPos = (lastPos + 1) % loglines.size
        loglines[nextPos] = line
        lastPos = nextPos
        if (startPos < 0) {
            startPos = 0
        } else if (startPos >= lastPos) {
            startPos = (lastPos + 1) % loglines.size
        }
    }

    override fun toString(): String {
        return StreamSupport.stream(spliterator(), false).collect(Collectors.joining("\n"))
    }

    override fun iterator(): LoglinesIterator {
        return LoglinesIterator()
    }

    inner class LoglinesIterator : MutableIterator<String?> {
        private var nextPos = startPos
        override fun hasNext(): Boolean {
            return nextPos >= 0 && nextPos < loglines.size
        }

        override fun next(): String? {
            if (!hasNext()) {
                return null
            }
            val nextLine = loglines[nextPos]
            when (nextPos) {
                lastPos -> {
                    nextPos = -1
                }

                loglines.size - 1 -> {
                    nextPos = 0
                }

                else -> {
                    nextPos++
                }
            }
            return nextLine
        }

        override fun remove() {
            throw NotImplementedError("Not implemented")
        }
    }
}