// SPDX-FileCopyrightText: Adam Evyčędo
//
// SPDX-License-Identifier: GPL-3.0-or-later

package xyz.apiote.bimba.czwek.api.responses

import xyz.apiote.bimba.czwek.api.structs.FeedInfoV1
import xyz.apiote.bimba.czwek.api.structs.FeedInfoV2
import xyz.apiote.fruchtfleisch.Reader
import java.io.InputStream

interface FeedsResponse {
	companion object {
		fun unmarshal(stream: InputStream): FeedsResponse {
			val reader = Reader(stream)
			return when (val v = reader.readUInt().toULong()) {
				// 0UL -> FeedsResponseDev.unmarshal(stream)
				1UL -> FeedsResponseV1.unmarshal(stream)
				2UL -> FeedsResponseV2.unmarshal(stream)
				else -> throw UnknownResponseVersion("Feeds", v)
			}
		}
	}
}

data class FeedsResponseV2(
	val feeds: List<FeedInfoV2>
) : FeedsResponse {
	companion object {
		fun unmarshal(stream: InputStream): FeedsResponseDev {
			val feeds = mutableListOf<FeedInfoV2>()
			val reader = Reader(stream)
			val n = reader.readUInt().toULong()
			for (i in 0UL until n) {
				feeds.add(FeedInfoV2.unmarshal(stream))
			}
			return FeedsResponseDev(feeds)
		}
	}
}

data class FeedsResponseV1(
	val feeds: List<FeedInfoV1>
) : FeedsResponse {
	companion object {
		fun unmarshal(stream: InputStream): FeedsResponseV1 {
			val feeds = mutableListOf<FeedInfoV1>()
			val reader = Reader(stream)
			val n = reader.readUInt().toULong()
			for (i in 0UL until n) {
				feeds.add(FeedInfoV1.unmarshal(stream))
			}
			return FeedsResponseV1(feeds)
		}
	}
}
