package eu.smoser.epv

import android.os.Bundle
import android.widget.Button
import android.widget.EditText
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.lifecycleScope
import java.lang.Exception

class ResultActivity : AppCompatActivity() {
    private var search = String()
    private var user = User(0, 0)

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

        if (intent.extras?.getString("search") !== null) {
            search = intent.extras?.getString("search")!!
        } else {
            onBackPressed()
        }

        lifecycleScope.executeAsyncTask(onPreExecute = {}, doInBackground = {
            val dao = AppDatabase.getInstance(this@ResultActivity).userDao()
            var tempUser = dao?.findById(search.toLong())
            if(tempUser == null) {
                tempUser = User(search.toLong(), 0)
                dao?.insert(tempUser)
            }
            tempUser
        }, onPostExecute = {
            user = it
            findViewById<TextView>(R.id.textViewId).text = user.uid.toString()
            setCurrentPrivilegien(user.privilegien)
        })

        findViewById<Button>(R.id.buttonSave).setOnClickListener {
            lifecycleScope.executeAsyncTask(onPreExecute = {}, doInBackground = {
                val dao = AppDatabase.getInstance(this@ResultActivity).userDao()
                dao?.updatePrivilegien(user.uid, getCurrentPrivilegien())
            }, onPostExecute = {
                onBackPressed()
            })
        }
        findViewById<Button>(R.id.buttonCancel).setOnClickListener {
            onBackPressed()
        }
        findViewById<Button>(R.id.buttonPlus).setOnClickListener {
            setCurrentPrivilegien(getCurrentPrivilegien() + getModifier())
        }
        findViewById<Button>(R.id.buttonMinus).setOnClickListener {
            setCurrentPrivilegien(getCurrentPrivilegien() - getModifier())
        }
    }

    private fun getCurrentPrivilegien() : Int {
        var ret = 0
        try {
            ret = Integer.parseInt(findViewById<EditText>(R.id.editTextNumberSigned).text.toString())
        } catch (e : Exception) {
            findViewById<EditText>(R.id.editTextNumberSigned).setText("0")
        }
        return ret
    }

    private fun setCurrentPrivilegien(newPriv: Int) {
        findViewById<EditText>(R.id.editTextNumberSigned).setText(newPriv.toString())
    }

    private fun getModifier() : Int {
        var ret = 0
        try {
            ret = Integer.parseInt(findViewById<EditText>(R.id.editTextNumber).text.toString())
        } catch (e : Exception) {
            findViewById<EditText>(R.id.editTextNumber).setText("0")
        }
        return ret
    }
}