package com.example.firefly_go_android

import android.app.Activity
import android.os.Environment
import libandroid.Libandroid
import java.io.File
import java.io.FileOutputStream

object FireflyModMenu {

    @Volatile
    private var isServerStarted = false

    @JvmStatic
    fun init(activity: Activity) {
        val appDataPath = File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), "FireflyGo").absolutePath
        val dataDir = File("$appDataPath/data")
        if (!dataDir.exists()) dataDir.mkdirs()

        if (!isServerStarted) {
            isServerStarted = true
            Thread {
                try {
                    val isCopyDone = copyRawFiles(dataDir)
                    if (isCopyDone) {
                        Libandroid.setPathDataLocal(appDataPath)
                        Libandroid.setServerRunning(true)
                    } else {
                        isServerStarted = false
                    }
                } catch (e: Exception) {
                    isServerStarted = false
                }
            }.start()
        }
    }

    private fun copyRawFiles(targetDir: File): Boolean {
        val files = listOf(
            "assets/data-in-game.json" to "data-in-game.json",
            "assets/freesr-data.json" to "freesr-data.json",
            "assets/version.json" to "version.json"
        )
        return try {
            for ((assetPath, name) in files) {
                val outFile = File(targetDir, name)
                if (!outFile.exists()) {
                    val inputStream =
                        FireflyModMenu::class.java.classLoader?.getResourceAsStream(assetPath)
                            ?: return false

                    inputStream.use { input ->
                        FileOutputStream(outFile).use { output ->
                            input.copyTo(output)
                            output.fd.sync()
                        }
                    }
                }
            }
            true
        } catch (e: Exception) {
            false
        }
    }
}