package ta1.cis.activity

import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.view.View
import android.widget.*
import kotlinx.android.synthetic.main.activity_edit_data_sekolah.*
import kotlinx.android.synthetic.main.activity_edit_pribadi.*
import kotlinx.android.synthetic.main.detail_pengumuman.*
import kotlinx.coroutines.*
import retrofit2.Call
import retrofit2.Response
import retrofit2.awaitResponse
import ta1.cis.R
import ta1.cis.api.RetrofitInstance
import ta1.cis.fragment.tabitem.D_PribadiFragment
import ta1.cis.helper.SharedPref
import ta1.cis.model.request.RequestEditPribadi
import ta1.cis.model.response.DataAkademis
import ta1.cis.model.response.EditPribadi
import ta1.cis.model.response.ResponseEditPribadi
import javax.security.auth.callback.Callback

class EditDataPribadiActivity : AppCompatActivity() {
    private lateinit var sharedPref: SharedPref
    private lateinit var radioGroup: RadioGroup
    private lateinit var btnEdit: Button
    private lateinit var agamaSpin: Spinner
    private lateinit var kabupatenSpin : Spinner
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_edit_pribadi)

        sharedPref = SharedPref(this)
        radioGroup = findViewById(R.id.radioGroupJk)
        btnEdit = findViewById(R.id.saveEditPribadi)
        setSupportActionBar(topAppBarEdit)
        supportActionBar?.setDisplayHomeAsUpEnabled(true)

        val anakKe = intent.getStringExtra("Anak_ke")
        var index = anakKe?.indexOf('/')
        var length = anakKe?.length
        var anak = ""
        for (i in 0 until index!!){
            anak+= anakKe?.get(i)
        }
        var jumlahTanggungan = ""
        if (length != null) {
            for(i in index+1 until length!! ){
                jumlahTanggungan += anakKe?.get(i)
            }
        }
        etAnakKe.setText(anak)
        etJlhAnak.setText(jumlahTanggungan)
        val NamaSiswa = intent.getStringExtra("Nama")
        val EditNamaSiswa: EditText = findViewById(R.id.etnama)
        EditNamaSiswa.setText(NamaSiswa)

        val TglLahirSiswa = sharedPref.getTanggal()
        val EditTglLahirSiswa: EditText = findViewById(R.id.etTglLahir)
        EditTglLahirSiswa.setText(TglLahirSiswa)

        val TempatLahirSiswa = sharedPref.getTempat()
        val EditTempatLahirSiswa = findViewById<EditText>(R.id.etTmptLahir)
        EditTempatLahirSiswa.setText(TempatLahirSiswa)

        if (intent.getStringExtra("Jenis_Kelamin").equals("Laki-laki")){
            radioGroup.check(R.id.etlakilaki)
        }else{
            radioGroup.check(R.id.etperempuan)
        }

        val AlamatSiswa = intent.getStringExtra("Alamat")
        val EditAlamatSiswa: EditText = findViewById(R.id.etAlamatpribadi)
        EditAlamatSiswa.setText(AlamatSiswa)

        val KodePos = intent.getStringExtra("Kode_Pos")
        val EditKodePos: EditText = findViewById(R.id.etKodePos)
        EditKodePos.setText(KodePos)

        val EmailSiswa = intent.getStringExtra("Email")
        val EditEmailSiswa: EditText = findViewById(R.id.etEmail)
        EditEmailSiswa.setText(EmailSiswa)

        val Hp1Siswa = intent.getStringExtra("Hp1")
        val EditHp1Siswa: EditText = findViewById(R.id.etHP1)
        if(Hp1Siswa == ""){
            EditHp1Siswa.setText("-")
        }else{
            EditHp1Siswa.setText(Hp1Siswa)
        }
        val Hp2Siswa = intent.getStringExtra("Hp2")
        val EditHp2Siswa: EditText = findViewById(R.id.etHP2)
        if(Hp2Siswa == ""){
            EditHp2Siswa.setText("-")
        }else{
            EditHp2Siswa.setText(Hp2Siswa)
        }
        val agama = intent.getStringExtra("Agama")
        agamaSpin = findViewById(R.id.agama_spinner)
        ArrayAdapter.createFromResource(
            this,
            R.array.agama_list,
            android.R.layout.simple_spinner_item
        ).also { adapter ->
            adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
            // Apply the adapter to the spinner
            agamaSpin.adapter = adapter
            agamaSpin.setSelection(getIndex(agamaSpin,agama))
        }

//        if (intent.getStringExtra("Gol_Darah").equals("A")){
//            radioGroup.check(R.id.etB)
//        } else {
//            radioGroup.check(R.id.etAB)
//        }

        var kabupaten = intent.getStringExtra("Kabupaten")
        if(kabupaten == "" || kabupaten == "null" || kabupaten == null){
            kabupaten = "Kabupaten"
        }
        kabupatenSpin = findViewById(R.id.kbptenPribadi)
        ArrayAdapter.createFromResource(
            this,
            R.array.kabupaten_list,
            android.R.layout.simple_spinner_item
        ).also { adapter ->
            adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
            kabupatenSpin.adapter = adapter
//            val apa = getIndex(kabupatenSpin,kabupaten)
            kabupatenSpin.setSelection(getIndex(kabupatenSpin,kabupaten))
//            kabupatenSpin.setSelection(getIndex(kabupatenSpin,kabupaten))
        }

        btnEdit.setOnClickListener {
            pb_pribadi.visibility = View.VISIBLE
            var jenis_kelamin = 0;
            if(etlakilaki.isChecked){
                jenis_kelamin = 1
            }else{
                jenis_kelamin = 2
            }
            var agama = agama_spinner.selectedItem.toString();
            var agamaId = 0;
            when(agama){
                "Kristen"->{
                    agamaId = 1
                }
                "Katolik" -> {
                    agamaId = 2
                }
                "Islam" -> {
                    agamaId = 3
                }
                "Hindu" -> {
                    agamaId = 4
                }
                "Buddha" -> {
                    agamaId = 5
                }
                "Konghucu" -> {
                    agamaId = 6
                }
            }
            var golDar = "";
            if(etA.isChecked){
                golDar = "1"
            }
            else if(etB.isChecked){
                golDar = "2"
            }
            else if(etAB.isChecked){
                golDar = "3"
            }
            else golDar = "4"
            val data = RequestEditPribadi(
                etnama.text.toString(),
                etTglLahir.text.toString(),
                etTmptLahir.text.toString(),
                etAlamatpribadi.text.toString(),
                etHP1.text.toString(),
                etHP2.text.toString(),
                etAnakKe.text.toString(),
                etJlhAnak.text.toString(),
                jenis_kelamin.toString(),
                agamaId.toString(),
                golDar,
                kbptenPribadi.selectedItem.toString(),
                etKodePos.text.toString(),
                etEmail.text.toString(),
                etTelepon.text.toString()
            );
            editData(data);

        }

        topAppBarEdit.setNavigationOnClickListener {
            onBackPressed()
        }
    }

    private fun getIndex(spinner: Spinner, data: String?): Int {
        for (i in 0 until spinner.count){
            if(spinner.getItemAtPosition(i).toString().equals(data)){
                return i
            }
        }
        return 0
    }

    private fun editData(datas:RequestEditPribadi){
        GlobalScope.launch(Dispatchers.IO){
            val response = RetrofitInstance.instanceRetrofit.updateDataPribadi("Bearer ${sharedPref.getTokenBearer()}",datas).awaitResponse()
            if (response.isSuccessful){
                var pribadi = response.body()?.data
                withContext(Dispatchers.Main){
                    delay(2000L)
                    pb_pribadi.visibility = View.VISIBLE
                    sharedPref.setStatusUpdate(2)
                    Toast.makeText(applicationContext,"Data sudah berhasil di update",Toast.LENGTH_LONG).show()
                    onBackPressed()
                }
            }
        }
    }
}