package com.webtoonviewer.utils

import android.content.Context
import android.util.Log
import java.io.File

class SharedPreferencesHelper(
    private val context: Context,
    private val fileName: String
) {

    fun saveData(key: String, value: String) {
        val sharedPreferences = context.getSharedPreferences(fileName, Context.MODE_PRIVATE)
        val editor = sharedPreferences.edit()
        editor.putString(key, value)
        editor.apply()
    }

    fun readData(key: String, defaultValue: String): String {
        val sharedPreferences = context.getSharedPreferences(fileName, Context.MODE_PRIVATE)
        return sharedPreferences.getString(key, defaultValue) ?: defaultValue
    }

    fun putBoolean(key: String, value: Boolean) {
        val sharedPreferences = context.getSharedPreferences(fileName, Context.MODE_PRIVATE)
        val editor = sharedPreferences.edit()
        editor.putBoolean(key, value)
        editor.apply()
    }

    fun getBoolean(key: String, defaultValue: Boolean): Boolean {
        val sharedPreferences = context.getSharedPreferences(fileName, Context.MODE_PRIVATE)
        return sharedPreferences.getBoolean(key, defaultValue) ?: defaultValue
    }

    fun getAllSharedPreferences(): MutableList<String> {
        val sharedPreferences = context.getSharedPreferences(fileName, Context.MODE_PRIVATE)
        val allEntries: Map<String, *> = sharedPreferences.all
        for ((key, value) in allEntries) {
            Log.d("SharedPreferences", "$key: $value")

        }
        return sharedPreferences.all.keys.toMutableList()
    }

    fun removeSpecificSharedPreference(key: String) {
        val sharedPreferences = context.getSharedPreferences(fileName, Context.MODE_PRIVATE)
        val editor = sharedPreferences.edit()
        editor.remove(key)
        editor.apply()  // or editor.commit()
    }

    fun clearAllSharedPreferences() {
        val sharedPreferences = context.getSharedPreferences(fileName, Context.MODE_PRIVATE)
        val editor = sharedPreferences.edit()
        editor.clear()
        editor.apply()  // or editor.commit()
    }

    private fun deleteSharedPreferencesFile(fileName: String) {
        val dir = context.filesDir.parentFile
        val sharedPrefsFile = File(dir, "shared_prefs/$fileName.xml")
        if (sharedPrefsFile.exists()) {
            sharedPrefsFile.delete()
        }
    }
}