package com.seatel.mobilehall.util.lang

import android.content.Context
import android.os.AsyncTask
import android.text.TextUtils
import android.util.Log
import com.seatel.mobilehall.data.realm.WordRealmObject
import com.seatel.mobilehall.util.SeatelUtils.Companion.optJSONObject
import io.realm.RealmObject
import org.json.JSONObject

class LanguageReadAsynctask(context: Context, response: JSONObject?) :
    AsyncTask<String, Void, List<RealmObject>>() {

    private var mContext: Context? = null
    private var mResponse: JSONObject? = null

    init {
        this.mContext = context
        this.mResponse = response
    }

    override fun doInBackground(vararg params: String?): List<RealmObject> {
        val words = ArrayList<RealmObject>()
//        var data = optJSONObject(mResponse, "data")

        val keyStrList = mResponse!!.keys()
        var objects: JSONObject
        var keyStr: String?
        var valueStr: String?
        var codeStr: String

        while (keyStrList.hasNext()) {
            keyStr = keyStrList.next()

            objects = optJSONObject(mResponse!!, keyStr)
//            Log.d("keyStrList", "keyStrList = $objects ")
            val languageCode = objects.keys()
            var word: WordRealmObject

            while (languageCode.hasNext()) {
                codeStr = languageCode.next()
                valueStr = objects.optString(codeStr)
//                Log.d("keyStrList", "sub===== $codeStr  $valueStr $keyStr")
                if (!TextUtils.isEmpty(valueStr)) {
                    word = WordRealmObject()
                    word.setKey(keyStr)
                    word.setLanguageCode(codeStr)
                    word.setValue(valueStr)
                    words.add(word)
                }
            }

        }
        mResponse = null
        return words
    }

    override fun onPostExecute(result: List<RealmObject>?) {
        if (result != null) {
            LanguageManager.getInstance(this.mContext!!).clearAll().saveAll(result)
            Log.d(javaClass.simpleName, "Support Language has been up ot date!")
        } else {
            Log.w(javaClass.simpleName, "Updating Support Language error!")
        }
    }

}