package mg.dot.feufaro.viewmodel

import cafe.adriel.voyager.core.model.ScreenModel
import cafe.adriel.voyager.core.model.screenModelScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import mg.dot.feufaro.DeepLinkHandler
import mg.dot.feufaro.FileRepository
import mg.dot.feufaro.solfa.Solfa
import mg.dot.feufaro.solfa.TUOEditState

class SolfaScreenModel(
    val fileRepository: FileRepository,
    val solfa: Solfa
) : ScreenModel {
    init {
        DeepLinkHandler.onSongReceived = { fileContent, filePath ->
            println("QR Scan: Chemin reçu, lancement du chargement...")
            loadExternalFile(filePath)
        }
    }

    fun loadExternalFile(path: String) {
            solfa.resetShared()
            solfa.parse(path)

            println("QR Scan: Chargement terminé pour $path")
    }

    fun loadNextInPlaylist() {
        solfa.loadNextInPlaylist()
    }

    fun reload() {
        solfa.loadSolfa()
    }

    fun loadCustomFile() {
        solfa.loadFile()
    }
    fun loadFromFile(path: String) {
        solfa.parse(path)
    }

    fun justCompile(path: String, content: String) {
        solfa.justBuild(path, content)
    }
    fun saveTUOEdit(editState: TUOEditState) {
        screenModelScope.launch(Dispatchers.IO) {
            solfa.saveTUOEdit(editState)
        }
    }
    fun newSolfa(metadata: PartitionMetadata) {
        screenModelScope.launch(Dispatchers.IO) {
            solfa.createNewSolfa(metadata)
        }
    }
    fun generateMidiFile(bpm: Float, path: String) {
        solfa.generateMidiFile(bpm, path)
    }
}