package ta1.cis.activity

import android.content.Intent
import android.os.Bundle
import android.view.View
import android.widget.Button
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import kotlinx.android.synthetic.main.activity_isi_kuesioner.*
import kotlinx.android.synthetic.main.fragment_kuesioner.*
import kotlinx.android.synthetic.main.isikuesioner_layout.*
import kotlinx.coroutines.*
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import retrofit2.awaitResponse
import ta1.cis.R
import ta1.cis.adapter.IsiKuisionerAdapter
import ta1.cis.api.RetrofitInstance
import ta1.cis.helper.SharedPref
import ta1.cis.model.request.Answare
import ta1.cis.model.request.KuisionerAnsware
import ta1.cis.model.response.*

class IsiKuesionerActivity : AppCompatActivity() {
    private lateinit var sharedPref: SharedPref
    private lateinit var idkuesioner: DataKuesioner
    var answare = mutableListOf<String>()
    lateinit var rvQuestion: RecyclerView
    lateinit var pertanyaan: List<DataItem>
    companion object{
        val DATA_KUESIONER : String = "DATA_KUESIONER"
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_isi_kuesioner)
        setSupportActionBar(kuesionerBar)
        supportActionBar?.setDisplayHomeAsUpEnabled(true)
        sharedPref = SharedPref(this)
        idkuesioner = intent.getParcelableExtra<ResponseKuesioner>("DATA_KUESIONER") as DataKuesioner
        findViewById<TextView>(R.id.JudulKuesioner).text = idkuesioner.nama
        findViewById<TextView>(R.id.InstruksiPengisian).text = idkuesioner.keterangan
        rvQuestion = findViewById(R.id.rvQuestion)
        pbKuesioner.visibility = View.VISIBLE
        fetchIsiKuesioner()
    }
    fun setAnsware(position:Int, selected:String){
        if(this.answare.size < (position + 1)){
            this.answare.add(position, selected)
        }else{
            selected.also { this.answare[position] = it }
        }
    }
    fun sendAnsware(button:Button){
        button.text= "Sedang mengirim data..."
        var _answares = mutableListOf<Answare>()
        var question = this.pertanyaan
        this.answare.forEachIndexed { index, s ->
            println(question[index])
            if(question[index].tipeOpsi.equals("C", ignoreCase = false)){
                val selected = s.split(",")
                selected.forEach {
                   if(it.trim() != ""){
                       _answares.add(index, Answare(
                           it,
                           sharedPref.getUsername(),
                           sharedPref.getUserId(),
                           question[index]?.kuesionerPertanyaanId,
                           question[index]?.kuesionerId
                       ))
                   }
                }
            }else if(question[index]?.tipeOpsi.equals("T", ignoreCase = false)
                || question[index]?.tipeOpsi.equals("R", ignoreCase = false)){
                _answares.add(index, Answare(
                    s,
                    sharedPref.getUsername(),
                    sharedPref.getUserId(),
                    question[index]?.kuesionerPertanyaanId,
                    question[index]?.kuesionerId
                ))
            }
        }
        var kuisionerAnsware = KuisionerAnsware(_answares)

        CoroutineScope(Dispatchers.IO).launch {
            val insert = RetrofitInstance.instanceRetrofit
                .sendKuesionerAnsware(sharedPref.getTokenBearer(),kuisionerAnsware).awaitResponse()
            if(insert.isSuccessful){
                withContext(Dispatchers.Main){
                    Toast.makeText(this@IsiKuesionerActivity,
                        "Success to send answare.", Toast.LENGTH_LONG)
                        .show()
                    this@IsiKuesionerActivity.startActivity(Intent(this@IsiKuesionerActivity, HomeActivity::class.java))
                    this@IsiKuesionerActivity.finish()
                }
            }else{
                withContext(Dispatchers.Main){
                    var kode = insert.errorBody().hashCode()
                    Toast.makeText(this@IsiKuesionerActivity,
                        "Kode Error : {$kode}", Toast.LENGTH_LONG)
                        .show()
                }
            }
        }
    }
    private fun fetchIsiKuesioner(){
        RetrofitInstance.instanceRetrofit.getPertanyaanKuesioner("Bearer ${sharedPref.getTokenBearer()}", idkuesioner.kuesionerId!!.toLong()).enqueue(object : Callback<ResponsePertanyaan>{
            override fun onResponse(
                call: Call<ResponsePertanyaan>,
                response: Response<ResponsePertanyaan>
            ) {
                val pertanyaan = response.body()
                val lpertanyaan: List<DataItem> = pertanyaan?.data as List<DataItem>
                this@IsiKuesionerActivity.pertanyaan = lpertanyaan
                for (dataItem in lpertanyaan){
                    this@IsiKuesionerActivity.answare.add("")
                }
                rvQuestion.layoutManager = LinearLayoutManager(this@IsiKuesionerActivity, LinearLayoutManager.VERTICAL, false)
                val adapter = IsiKuisionerAdapter(this@IsiKuesionerActivity, lpertanyaan, answare)
                rvQuestion.adapter = adapter

                pbKuesioner.visibility = View.GONE
                pertanyaan?.let {
                    var mypertanyaan = it.data

                }
            }

            override fun onFailure(call: Call<ResponsePertanyaan>, t: Throwable) {
                Toast.makeText(this@IsiKuesionerActivity, t.message, Toast.LENGTH_LONG).show()

                pbKuesioner.visibility = View.GONE
            }

        })
    }

}