package com.github.jonathanxd.dracon.pijul.diff
import com.google.gson.GsonBuilder
import com.google.gson.annotations.SerializedName
import com.intellij.openapi.vcs.FileStatus
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.map
import kotlin.reflect.javaType
import kotlin.reflect.typeOf
object PijulDiffJson {
val GSON = GsonBuilder().disableHtmlEscaping().create()
// TODO: Use Kotlin Flow and Flow-based Json reading
@OptIn(ExperimentalStdlibApi::class)
fun parseJson(json: String): List<ChangeEntry> =
GSON.fromJson<Map<String, List<ChangeData>>>(json, typeOf<Map<String, List<ChangeData>>>().javaType).entries.map {
ChangeEntry(it.key, it.value)
}
}
fun List<ChangeEntry>.toFileStatusMap(): Map<String, List<FileStatus>> =
this.associateBy { it.path }.mapValues {
it.value.data.map { it.toFileStatus() }
}
fun ChangeData.toFileStatus(): FileStatus =
when (this.operation) {
"replacement", "edit" -> FileStatus.MODIFIED
"file move" -> FileStatus.ADDED
"file del" -> FileStatus.DELETED
"file undel" -> FileStatus.ADDED
"file add" -> FileStatus.ADDED
// "solve name conflict" -> ?
// "unsolve name conflict" -> ?
// "solve order conflict" -> ?
// "unsolve order conflict" -> ?
// "resurrect zombies" -> ????????????????????
else -> FileStatus.UNKNOWN
}
data class ChangeEntry(val path: String, val data: List<ChangeData>)
data class ChangeData(@SerializedName("operation") val operation: String, @SerializedName("line") val line: Any?)