package ui

import data.FileUtilities
import data.Message
import ui.interfaces.UserNotifier
import ui.interfaces.VideoFileSelector
import java.io.File
import java.nio.file.Paths
import java.util.ResourceBundle
import java.util.logging.Logger
import javax.swing.JFileChooser
import kotlin.system.exitProcess

class JFileChooserVideoFileSelector(
    private val notifier: UserNotifier = JOptionPaneUserNotifier(),
    private val logger: Logger = Logger.getLogger(JFileChooserVideoFileSelector::class.java.name),
    private val messages: ResourceBundle = Message().messages,
    private var lastDirectory: File = File(Paths.get(System.getProperty("user.home"), "Downloads").toString()),
    private val fileUtilities: FileUtilities = FileUtilities()
) : VideoFileSelector {

    override fun selectVideoFiles(many: Boolean): List<File> {
        val fileChooser = createFileChooser(many)
        val userSelection = fileChooser.showOpenDialog(null)
        return if (userSelection == JFileChooser.APPROVE_OPTION) {
            if (fileChooser.selectedFiles.isNotEmpty()) {
                val filteredSelectedFiles = fileChooser.selectedFiles.filter { !fileUtilities.areItEmpty(it) }
                if (filteredSelectedFiles.isNotEmpty()) {
                    handleFileSelection(filteredSelectedFiles)
                } else {
                    notifier.showWarning(
                        "Todos Arquivos selecionados de ${fileChooser.selectedFiles.first().parentFile} estão vazios!\nSelecione outros arquivos"
                    )
                    selectVideoFiles(many)
                }
            } else if (fileChooser.selectedFile != null) {
                if (fileUtilities.areItEmpty(fileChooser.selectedFile)) {
                    notifier.showWarning(
                        "Arquivo ${fileChooser.selectedFile.name} está vazio!\nSelecione outro arquivo"
                    )
                    selectVideoFiles(many)
                } else {
                    handleFileSelection(listOf(fileChooser.selectedFile))
                }
            } else {
                throw RuntimeException("Can't define the file(s) in fileChooser!")
            }
        } else {
            exitProcess(0)
        }
    }

    private fun createFileChooser(many: Boolean): JFileChooser {
        return JFileChooser().apply {
            currentDirectory = lastDirectory
            fileSelectionMode = JFileChooser.FILES_ONLY
            if (many) {
                isMultiSelectionEnabled = true
            }
            dialogTitle = messages.getString("dialogTitle")
        }
    }

    private fun handleFileSelection(files: List<File>): List<File> {
        if (files.size < 2) {
            files.forEach { file ->
                logger.info("Selected file: ${file.absolutePath} is ${file.length()} in size")
                if (file.length() <= 2_000_000_000 && file.extension == "mp4") {
                    if (notifier.smallFile() == 0) {
                        return selectVideoFiles()
                    } else {
                        logger.info("User choose not to proceed.")
                        exitProcess(0)
                    }
                }
            }
        }
        lastDirectory = files.first().parentFile
        return files
    }
}

melhore esse código com boas práticas com SOLID E CLEANCODE