@file:Suppress("HardCodedStringLiteral")

package eu.gaudian.translator.model.repository


import android.content.Context
import android.content.Intent
import android.net.Uri
import android.provider.MediaStore
import eu.gaudian.translator.utils.Log
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import kotlinx.serialization.json.Json
import java.io.IOException
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale

class VocabularyFileSaver(private val context: Context, private val repository: VocabularyRepository) {

    fun createSaveDocumentIntent(suggestedFilename: String): Intent {
        return Intent(Intent.ACTION_CREATE_DOCUMENT).apply {
            addCategory(Intent.CATEGORY_OPENABLE)
            type = "application/json" // Adjust as needed
            putExtra(Intent.EXTRA_TITLE, suggestedFilename)
        }
    }

    suspend fun saveRepositoryToUri(uri: Uri) {
        withContext(Dispatchers.IO) {
            try {
                context.contentResolver.openOutputStream(uri)?.use { outputStream ->
                    val vocabularyItems = repository.getAllVocabularyItems()
                    if (vocabularyItems.isNotEmpty()) {
                        val jsonString = Json.encodeToString(vocabularyItems)
                        outputStream.write(jsonString.toByteArray())
                        val filename = getFileNameFromUri(uri)
                        Log.d(TAG, "File saved: $filename")
                    } else {
                        Log.e(TAG, "No vocabulary items to save.")
                    }
                }
            } catch (e: IOException) {
                Log.e(TAG, "Error saving: ${e.message}", e)
            }
        }
    }

    suspend fun saveCategoryToUri(uri: Uri, categoryId: Int) {
        withContext(Dispatchers.IO) {
            try {
                context.contentResolver.openOutputStream(uri)?.use { outputStream ->
                    val vocabularyItems = repository.getVocabularyItemsByCategory(categoryId)
                    if (vocabularyItems.isNotEmpty()) {
                        val jsonString = Json.encodeToString(vocabularyItems)
                        outputStream.write(jsonString.toByteArray())
                        val filename = getFileNameFromUri(uri)
                        Log.d(TAG, "File saved for category $categoryId: $filename")
                    } else {
                        Log.e(TAG, "No vocabulary items to save for category $categoryId.")
                    }
                }
            } catch (e: IOException) {
                Log.e(TAG, "Error saving for category $categoryId: ${e.message}", e)
            }
        }
    }


    fun generateFilename(): String {
        val timeStamp = SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(Date())
        return "vocabulary_$timeStamp.json"
    }

    fun generateFilenameForCategory(categoryId: Int): String {
        val timeStamp = SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(Date())
        return "vocabulary_category_$categoryId$timeStamp.json"
    }

    fun getFileNameFromUri(uri: Uri): String {
        var fileName = "unknown_file"
        if (uri.scheme == "content") {
            context.contentResolver.query(uri, null, null, null, null)?.use { cursor ->
                if (cursor.moveToFirst()) {
                    val displayNameIndex = cursor.getColumnIndex(MediaStore.MediaColumns.DISPLAY_NAME)
                    if (displayNameIndex != -1) {
                        fileName = cursor.getString(displayNameIndex)
                    }
                }
            }
        } else if (uri.scheme == "file") {
            fileName = uri.lastPathSegment ?: fileName
        }
        return fileName
    }

    companion object {
        private const val TAG = "VocabularyFileSaver"
    }
}