package de.leopoldluley.filebase.controller

import de.leopoldluley.filebase.Extensions.toFXImage
import de.leopoldluley.filebase.Utils
import de.leopoldluley.filebase.models.Entry
import de.leopoldluley.filebase.models.FileType
import javafx.scene.image.Image
import tornadofx.*
import java.io.File

class IconCtrl : Controller() {
    private val fileCtrl: FileCtrl by inject()

    private val cache = mutableMapOf<String, Image>()
    private val common = mapOf(
            FileType.Other          to img("/icon/common/Other.png"),
            FileType.Image          to img("/icon/common/Image.png"),
            FileType.Video          to img("/icon/common/Video.png"),
            FileType.Audio          to img("/icon/common/Audio.png"),
            FileType.Document       to img("/icon/common/Document.png"),
            FileType.Text           to img("/icon/common/Text.png"),
            FileType.Application    to img("/icon/common/Application.png"),
            FileType.Folder         to img("/icon/common/Folder.png")
    )

    private val nativeIcons: Boolean
    init {
        val test = sun.awt.shell.ShellFolder.getShellFolder(File(System.getProperty("user.home"))).getIcon(true)
        nativeIcons = test != null
    }

    fun getIcon(entry: Entry) = if (nativeIcons) getNativeIcon(entry) else getCommonIcon(entry)

    private fun getNativeIcon(entry: Entry): Image {
        val path = fileCtrl.getPathFor(entry)
        val extension = Utils.getFileExtension(path)
        if (cache.contains(extension)) {
            return cache[extension]!!
        } else {
            val img = sun.awt.shell.ShellFolder.getShellFolder(path.toFile()).getIcon(true)
            val image = img?.toFXImage()
            if (image != null) {
                cache.put(extension, image)
                return image
            } else {
                return getCommonIcon(entry)
            }
        }
    }

    private fun getCommonIcon(entry: Entry): Image {
        return common[entry.type]!!
    }

    private fun img(path: String): Image = Image(resources.stream(path))

}