package com.assimilate.alltrans.viewui

import android.os.AsyncTask
import android.os.Bundle
import android.widget.Button
import android.widget.EditText
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import com.assimilate.alltrans.R
import org.json.JSONArray
import org.json.JSONException
import java.io.BufferedReader
import java.io.InputStreamReader
import java.net.HttpURLConnection
import java.net.URL

class DicActivity : AppCompatActivity() {

    private lateinit var editTextWord: EditText
    private lateinit var buttonSearch: Button
    private lateinit var textViewDefinition: TextView

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_dic)

        editTextWord = findViewById(R.id.editTextWord)
        buttonSearch = findViewById(R.id.buttonSearch)
        textViewDefinition = findViewById(R.id.textViewDefinition)

        buttonSearch.setOnClickListener {
            val word = editTextWord.text.toString().trim()
            if (word.isNotEmpty()) {
                FetchDefinitionTask().execute(word)
            }
        }
    }

    private inner class FetchDefinitionTask : AsyncTask<String, Void, String?>() {
        override fun doInBackground(vararg params: String): String? {
            val word = params[0]
            val apiUrl = "https://api.dictionaryapi.dev/api/v2/entries/en/$word"
            return try {
                val url = URL(apiUrl)
                val urlConnection = url.openConnection() as HttpURLConnection
                urlConnection.requestMethod = "GET"
                val responseCode = urlConnection.responseCode
                if (responseCode == HttpURLConnection.HTTP_OK) {
                    val inputStream = BufferedReader(InputStreamReader(urlConnection.inputStream))
                    val response = StringBuilder()
                    var inputLine: String?
                    while (inputStream.readLine().also { inputLine = it } != null) {
                        response.append(inputLine)
                    }
                    inputStream.close()
                    response.toString()
                } else {
                    null
                }
            } catch (e: Exception) {
                e.printStackTrace()
                null
            }
        }

        override fun onPostExecute(result: String?) {
            if (result != null) {
                try {
                    val jsonArray = JSONArray(result)
                    val jsonObject = jsonArray.getJSONObject(0)
                    val meanings = jsonObject.getJSONArray("meanings")
                    val meaning = meanings.getJSONObject(0)
                    val definitions = meaning.getJSONArray("definitions")
                    val definition = definitions.getJSONObject(0)
                    val definitionText = definition.getString("definition")
                    textViewDefinition.text = definitionText
                } catch (e: JSONException) {
                    e.printStackTrace()
                    textViewDefinition.text = "Error parsing definition"
                }
            } else {
                textViewDefinition.text = "Definition not found"
            }
        }
    }
}
