package com.dowstats.service.w40k.helpscripts

import com.dowstats.data.rgd.RgdData
import org.springframework.stereotype.Service
import java.io.PrintWriter

@Service
class RgdService {

    fun getRgdDiff(first: List<RgdData>?, second: List<RgdData>?, path: String = ""): String {
        var diff = ""
        first?.sortedBy { it.name }?.forEach{rgdFirst ->
            val name = rgdFirst.name
            val rgdSecond = second?.find{it.name == name}
            if(rgdFirst != rgdSecond){
                val firstValue = rgdFirst.value
                when {
                    firstValue is List<*> && rgdSecond?.value is List<*> -> {
                        diff += getRgdDiff(firstValue as List<RgdData>, rgdSecond.value as List<RgdData>, "$path$name\\")
                    }
                    rgdFirst.value is List<*> -> {
                        diff += (path + name + " NEW" + "\n")
                    }
                    else -> {
                        diff += (path + name + ": " + rgdSecond?.value + "->" + rgdFirst.value + "\n")
                    }
                }
            }
        }
        val firstNames = first?.map { it.name }
        second?.filterNot { firstNames?.contains(it.name) == true }?.forEach {
            diff += (path + it.name + " REMOVED" + "\n")
        }
        return diff
    }

    // Удалить как будет готова вики
    fun printRgdDiff(first: List<RgdData>?, second: List<RgdData>?, path: String = "", out: PrintWriter = PrintWriter(
        System.out
    )
    ){
        first?.sortedBy { it.name }?.forEach{rgdFirst ->
            val name = rgdFirst.name
            val rgdSecond = second?.find{it.name == name}
            if(rgdFirst != rgdSecond){
                val firstValue = rgdFirst.value
                when {
                    firstValue is List<*> && rgdSecond?.value is List<*> -> {
                        printRgdDiff(firstValue as List<RgdData>, rgdSecond.value as List<RgdData>, "$path$name\\", out)
                    }
                    rgdFirst.value is List<*> -> {
                        out.println(path + name + " NEW")
                    }
                    else -> {
                        out.println(path + name + ": " + rgdSecond?.value + "->" + rgdFirst.value)
                    }
                }
            }
        }
        val firstNames = first?.map { it.name }
        second?.filterNot { firstNames?.contains(it.name) == true }?.forEach {
            out.println(path + it.name + " REMOVED")
        }
    }
}