package net.sergeych.toread.fb2

object Fb2Format {
    const val Namespace = "http://www.gribuser.ru/xml/fictionbook/2.0"
    const val XLinkNamespace = "http://www.w3.org/1999/xlink"

    fun parseXml(xml: String): Fb2Book = Fb2XmlMapper.fromXml(xml)

    fun parse(input: ByteArray, fileName: String? = null): Fb2Book {
        val xml = if (looksLikeZip(input) || fileName?.endsWith(".zip", ignoreCase = true) == true) {
            Fb2Zip.extractFb2Xml(input)
        } else {
            Fb2XmlEncoding.decodeXml(input)
        }
        return parseXml(xml)
    }

    fun exportXml(book: Fb2Book): String = Fb2XmlMapper.toXml(book)

    fun exportZip(book: Fb2Book, entryName: String = "book.fb2"): ByteArray {
        require(entryName.endsWith(".fb2", ignoreCase = true)) { "FB2 ZIP entry name should end with .fb2" }
        return Fb2Zip.createStoredZip(entryName, exportXml(book).encodeToByteArray())
    }

    private fun looksLikeZip(input: ByteArray): Boolean =
        input.size >= 4 &&
            input[0] == 'P'.code.toByte() &&
            input[1] == 'K'.code.toByte() &&
            input[2] == 3.toByte() &&
            input[3] == 4.toByte()
}
