package com.autotech.we1l.app

import android.content.Context
import android.os.Environment
import com.autotech.we1l.tools.FOLDER_NAME
import com.autotech.we1l.tools.SETTINGS_FOLDER_NAME
import com.autotech.we1l.tools.SHARED_PREFERENCES_NAME
import org.json.JSONObject
import java.io.File
import java.io.FileInputStream
import java.io.FileOutputStream
import java.io.IOException
import java.nio.charset.Charset

object AppLanguage {

    lateinit var language: String
    private lateinit var languageJSON: JSONObject

    fun init(context: Context) {
        loadLanguageSettings(context)
        languageJSON = loadJSON(context)!!
    }

    fun getString(stringId: String): String {
        return try {
            languageJSON.getString(stringId)
        } catch (e: Exception) {
            ""
        }
    }

    fun saveLanguageSettings(context: Context, language: String) {
        this.language = language
        val sharedPreferences = context.getSharedPreferences(SHARED_PREFERENCES_NAME, Context.MODE_PRIVATE)
        sharedPreferences.edit().putString("language", language).apply()
    }

    private fun loadLanguageSettings(context: Context) {
        val sharedPreferences = context.getSharedPreferences(SHARED_PREFERENCES_NAME, Context.MODE_PRIVATE)
        language = sharedPreferences.getString("language", "en")!!
    }

    fun saveLanguageFile(context: Context?, byteArray: ByteArray?) {
        val langFileDir = File(context?.cacheDir?.absolutePath +
                FOLDER_NAME + SETTINGS_FOLDER_NAME)
        try {
            if (!langFileDir.exists())
                langFileDir.mkdirs()
            val languageFile = File(langFileDir, "$language.json")
            languageFile.createNewFile()
            val fo = FileOutputStream(languageFile)
            fo.write(byteArray)
            fo.flush()
            fo.close()
        } catch (e: IOException) {

        }
    }

    fun loadJSONObject() {
        val langFileDir = File(Environment.getExternalStorageDirectory().absolutePath +
                FOLDER_NAME + SETTINGS_FOLDER_NAME)

        try {
            if (!langFileDir.exists())
                langFileDir.mkdirs()
            val languageFile = File(langFileDir, "$language.json")
            languageFile.createNewFile()
            val fo = FileOutputStream(languageFile)
//            fo.write(json.toString().toByteArray())
            fo.flush()
            fo.close()
        } catch (e: IOException) {
            e.printStackTrace()
        }
    }

    private fun loadJSONFromAsset(context: Context): JSONObject? {
        val json: String?
        try {
            val inputStream = context.assets.open("en.json")
            val size = inputStream.available()
            val buffer = ByteArray(size)
            inputStream.read(buffer)
            inputStream.close()
            json = String(buffer, Charset.defaultCharset())
        } catch (ex: IOException) {
            ex.printStackTrace()
            language = "en"
            return loadJSONFromAsset(context)
        }

        return JSONObject(json.apply {
            replace("""\\""", """\""")
        })
    }

    private fun loadJSON(context: Context): JSONObject? {
        val json: String?
        try {
            val inputStream = FileInputStream(File(context.cacheDir.absolutePath + FOLDER_NAME + SETTINGS_FOLDER_NAME, "$language.json"))
            val size = inputStream.available()
            val buffer = ByteArray(size)
            inputStream.read(buffer)
            inputStream.close()
            json = String(buffer, Charset.defaultCharset())
        } catch (ex: IOException) {
            ex.printStackTrace()
            if (language == "en") {
                return loadJSONFromAsset(context)
            }
            language = "en"
            return loadJSON(context)
        }

        return JSONObject(json.apply {
            replace("""\\""", """\""")
        })
    }

//    private fun readFromFile(): String {
//
//        var ret = ""
//        var inputStream: InputStream? = null
//        try {
//            inputStream = openFileInput("names.json")
//
//            if (inputStream != null) {
//                val inputStreamReader = InputStreamReader(inputStream)
//                val bufferedReader = BufferedReader(inputStreamReader)
//                var receiveString = ""
//                val stringBuilder = StringBuilder()
//
//                while ((receiveString = bufferedReader.readLine()) != null) {
//                    stringBuilder.append(receiveString)
//                }
//
//                ret = stringBuilder.toString()
//            }
//        } catch (e: FileNotFoundException) {
//            Log.e("login activity", "File not found: " + e.toString())
//        } catch (e: IOException) {
//            Log.e("login activity", "Can not read file: " + e.toString())
//        } finally {
//            try {
//                inputStream!!.close()
//            } catch (e: IOException) {
//                e.printStackTrace()
//            }
//
//        }
//
//        return ret
//    }


}
