package com.dowstats.service.w40k

import com.dowstats.configuration.StorageConfig
import org.slf4j.LoggerFactory
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Service
import java.awt.image.BufferedImage
import java.io.File
import javax.imageio.ImageIO


@Service
class IconsService @Autowired constructor(
    val storageConfig: StorageConfig,
) {

    val log = LoggerFactory.getLogger(IconsService::class.java)

    /** Конвертирует иконку tga->jpeg и возвращает путь до неё
     * @param pathToTgaIcon - путь до иконки
     * @return путь до сконвертированной иконки
     */
    fun convertTgaToJpegImage(iconPathInMod: String, pathToTgaIcon: String, modName: String? = null, convertHere: Boolean = false): String? {
        try{

            val image: BufferedImage = if(File(pathToTgaIcon).exists()) {
                try {
                    ImageIO.read(File(pathToTgaIcon))
                } catch (e: NoClassDefFoundError) {
                    log.warn("Can't convert icon $iconPathInMod", e)
                    return null
                }

            } else if (File(pathToTgaIcon.lowercase()).exists()) {
                ImageIO.read(File(pathToTgaIcon.lowercase()))
            } else return null

            val modFolder = modName?.let { "${File.separator}$modName" } ?: ""

            val pathToSave = if(!convertHere){
                "${storageConfig.iconsStorage.replace("/", File.separator)}$modFolder" +
                        "${File.separator}${iconPathInMod.lowercase().replace("/", File.separator).replace("\\", File.separator)}.png"
                } else {
                pathToTgaIcon.replace(".dds", ".tga")
            }

            val directoryToSave = File(pathToSave.split(File.separator).dropLast(1).joinToString (File.separator))
            if(!directoryToSave.exists()) directoryToSave.mkdirs()

            return if (!ImageIO.write(image, "png", File(pathToSave))) {
                null
            } else {
                pathToSave.replace("${storageConfig.iconsStorage.replace("/", File.separator)}${File.separator}", "")
                    .replace("${File.separator}${File.separator}","${File.separator}")
            }
        } catch (e: Exception) {
            log.warn("Can't convert icon $iconPathInMod", e)
            return null
        }

    }

    fun returnIcon(modName: String, raceIconFolder: String, iconName: String): ByteArray?  {
        val pathToIcon = "${storageConfig.iconsStorage.replace("/", File.separator)}${File.separator}$modName${File.separator}$raceIconFolder${File.separator}${iconName.lowercase()}"
       return File(pathToIcon).readBytes()
    }

}
