Skip to content

Commit

Permalink
tp10 solution
Browse files Browse the repository at this point in the history
  • Loading branch information
ctruchi committed Feb 17, 2025
1 parent e13c5c7 commit dfb2feb
Showing 1 changed file with 53 additions and 18 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -2,40 +2,75 @@ package fmt.kotlin.fundamentals

import java.io.InputStream
import java.nio.file.Path
import java.util.UUID
import java.util.*
import kotlin.io.path.*

class InventoryFileRepository(
val basePath: Path
) : InventoryRepository {

override fun addCellar(cellar: Cellar): Entity<Cellar> {
TODO("Not yet implemented")
}
override fun addCellar(cellar: Cellar) = Entity(
id = newId(),
data = cellar
)
.also { cellarEntity ->
basePath.resolve(cellarEntity.id).createDirectory()

cellar.bottles.forEach {
addBottle(it, cellarEntity.id)
}
}

override fun addBottle(bottle: Bottle, cellarId: String): Entity<Bottle> {
TODO("Not yet implemented")
}
val dirPath = basePath.resolve(cellarId)
if (dirPath.notExists()) {
throw IllegalArgumentException("Cellar does not exists: $cellarId")
}
val bottleEntity = Entity(
id = newId(),
data = bottle
)
dirPath.resolve(bottleEntity.id).writeText("${bottle.name},${bottle.year}")

override fun findBottles(cellarId: String): List<Entity<Bottle>> {
TODO("Not yet implemented")
return bottleEntity
}

override fun findCellarId(bottleId: String): String? {
TODO("Not yet implemented")
}
override fun findBottles(cellarId: String) =
basePath.resolve(cellarId).toFile().listFiles()!!.map {
Entity(
it.name,
it.readText().toBottle()
)
}

override fun findAllCellarIds(): List<String> {
TODO("Not yet implemented")
}

override fun findCellarId(bottleId: String) =
basePath.listDirectoryEntries().firstOrNull {
it.toFile().list()?.any { it == bottleId } ?: false
}?.name


override fun findAllCellarIds() = basePath.toFile().list()!!.toList()

override fun clear(cellarId: String) {
TODO("Not yet implemented")
basePath.resolve(cellarId).toFile().deleteRecursively()
}

override fun importBottle(cellarId: String, stream: InputStream): Bottle {
TODO("Not yet implemented")
}
override fun importBottle(cellarId: String, stream: InputStream) =
stream.reader()
.use {
it.readText()
}
.toBottle()
.also {
addBottle(it, cellarId)
}

companion object {
private fun newId() = UUID.randomUUID().toString()
}
}

private fun String.toBottle() = split(",").let {
Bottle(it.first(), it.get(1).toInt())
}

0 comments on commit dfb2feb

Please sign in to comment.