package ta1.cis.activity

import android.app.TimePickerDialog
import android.os.Bundle
import android.text.format.DateFormat
import android.util.Log
import android.view.View
import android.widget.TimePicker
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.google.android.material.datepicker.CalendarConstraints
import com.google.android.material.datepicker.DateValidatorPointForward
import com.google.android.material.datepicker.MaterialDatePicker
import kotlinx.android.synthetic.main.activity_edit_izin_bermalam.*
import kotlinx.android.synthetic.main.activity_edit_izin_keluar.*
import kotlinx.android.synthetic.main.activity_request_izin_keluar.*
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import retrofit2.awaitResponse
import ta1.cis.R
import ta1.cis.api.RetrofitInstance
import ta1.cis.helper.SharedPref
import ta1.cis.model.request.IKRequest
import ta1.cis.model.response.DataIzinKeluar
import java.text.SimpleDateFormat
import java.util.*

class EditIzinKeluar : AppCompatActivity() {

    companion object{
        var DATA_IZIN_KELUAR = "DATA_IZIN_KELUAR"
    }


    private lateinit var waktuBerangkat :String
    private lateinit var waktuKembali :String
    private lateinit var dataIzinKeluar: DataIzinKeluar
    private lateinit var sharedPref: SharedPref

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_edit_izin_keluar)
        dataIzinKeluar = intent.getParcelableExtra<DataIzinKeluar>(DATA_IZIN_KELUAR) as DataIzinKeluar
        sharedPref = SharedPref(this)
        bindData()
        btn_editBerangkatIK.setOnClickListener {
            getDate(0)
        }
        btn_editKembaliIK.setOnClickListener {
            getDate(1)
        }
        buatEditIk.setOnClickListener {
            pb_editik.visibility = View.VISIBLE
            editData()
        }
        batalEditIk.setOnClickListener {
            cancelIk()
        }
    }

    private fun cancelIk() {
        GlobalScope.launch(Dispatchers.IO) {
            var response = RetrofitInstance.instanceRetrofit.cancelIk(dataIzinKeluar.izinKeluarId!!.toLong(),"Bearer ${sharedPref.getTokenBearer()}").awaitResponse()
            if(response.isSuccessful)
            withContext(Dispatchers.Main){
                Toast.makeText(baseContext,"IK sudah berhasil di update",Toast.LENGTH_LONG).show()
                onBackPressed()
            }else{
                Log.d("ErrorCancel","Ada Bermasalah")
            }
        }
    }

    private fun editData() {
        if(validateAllInput() == 1){
            var data = IKRequest(
                tgl_berangkat_editIK.text.toString(),
                tgl_kembali_editIK.text.toString(),
                keperluan_ik_edit.text.toString()
            )
            sendDataToServer(data)
        }else{

        }

    }

    private fun sendDataToServer(data: IKRequest) {
        GlobalScope.launch(Dispatchers.IO) {
            val response = RetrofitInstance.instanceRetrofit.editIk(
                dataIzinKeluar.izinKeluarId!!.toLong(),
                sharedPref.getDimId().toLong(),
                data,"Bearer ${sharedPref.getTokenBearer()}").awaitResponse()

            if(response.isSuccessful){
                withContext(Dispatchers.Main){
                    Toast.makeText(baseContext,"IK Berhasil Di Update",Toast.LENGTH_LONG).show()
                    pb_editik.visibility = View.GONE
                    onBackPressed()
                }
            }else{
                Log.d("EditError",response.errorBody().toString())
                pb_editik.visibility = View.GONE
            }

        }
    }

    private fun validateAllInput() : Int{
        if(tgl_berangkat_editIK.text.isNullOrBlank() || tgl_kembali_editIK.text.isNullOrBlank() || keperluan_ik_edit.text.isNullOrBlank()){
            Toast.makeText(this@EditIzinKeluar,"Harap mengisi seluruh field",Toast.LENGTH_LONG).show()
            pb_editik.visibility = View.GONE
            return 0
        }else{
            var validateTgl = validate()
            if(validateTgl == -1){
                return 1
            }
        }
        return 0
    }

    private fun bindData() {
        tgl_berangkat_editIK.setText(dataIzinKeluar.rencanaBerangkat)
        tgl_kembali_editIK.setText(dataIzinKeluar.rencanaKembali)
        keperluan_ik_edit.setText(dataIzinKeluar.keperluanIk)
    }

    fun validate() : Int{
        var cek_count = 0;
        val sdf = SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
        var date1  = sdf.parse(tgl_berangkat_editIK.text.toString());
        var date2 = sdf.parse(tgl_kembali_editIK.text.toString());
        var compare = -2
        var compareBerangkat = -2
        if(date1 != null && date2 !=  null){
            compare = date1.compareTo(date2)
            compareBerangkat = date2.compareTo(date1)
        }
        Log.d("Compare",compare.toString())
        if(compare == 1 || compare == 0){
            Toast.makeText(applicationContext,"Tanggal Kembali sama atau kurang dari tanggal berangkat",
                Toast.LENGTH_SHORT).show()
        }else{
            compare = -1
        }
        if(compareBerangkat == -1 || compareBerangkat == 0){
            Toast.makeText(applicationContext,"Tanggal Berangkat sama atau lebih dari tanggal kembali",
                Toast.LENGTH_SHORT).show()
        }else{
            compareBerangkat = 1
        }
        if(compare == -1 && compareBerangkat == 1){
            pb_editik.visibility = View.GONE
            return compare
        }
        return 0;
    }


    private fun getDate(jenis: Int) {
        val mcurrentDate: Calendar = Calendar.getInstance()
        val mYear: Int = mcurrentDate.get(Calendar.YEAR)
        val mMonth: Int = mcurrentDate.get(Calendar.MONTH)
        val mDay: Int = mcurrentDate.get(Calendar.DAY_OF_MONTH)
        mcurrentDate.add(Calendar.DATE,0);
        val constraintBuilder = CalendarConstraints.Builder().setValidator(DateValidatorPointForward.from(mcurrentDate.timeInMillis))
        val picker = MaterialDatePicker.Builder
            .datePicker()
            .setTitleText("Pilih Waktu")
            .setSelection(mcurrentDate.timeInMillis)
            .setCalendarConstraints(constraintBuilder.build())
            .build()

        picker.show(supportFragmentManager,"tag")
        picker.addOnPositiveButtonClickListener { selection: Long ->

            val timeZoneUTC = TimeZone.getDefault()
            val offsetFromUTC = timeZoneUTC.getOffset(Date().time) * -1
            val simpleFormat = SimpleDateFormat("yyyy-MM-dd", Locale.US)
            val date = Date(selection + offsetFromUTC)
            val mcurrentDate: Calendar = Calendar.getInstance()
//            var waktuBerangkat :String = simpleFormat.format(date)
            if(jenis == 0){
                waktuBerangkat = simpleFormat.format(date)
            }else{
                waktuKembali = simpleFormat.format(date)
            }
            val timePicker = TimePickerDialog(this,object : TimePickerDialog.OnTimeSetListener{
                override fun onTimeSet(view: TimePicker?, hourOfDay: Int, minute: Int) {
                    if(jenis == 0){
                        waktuBerangkat += " ${hourOfDay}:${minute}:00"
                        tgl_berangkat_editIK.setText(waktuBerangkat.toString())
                    }else{
                        waktuKembali += " ${hourOfDay}:${minute}:00"
                        tgl_kembali_editIK.setText(waktuKembali.toString())
                    }
                }
            },mcurrentDate.get(Calendar.HOUR_OF_DAY), mcurrentDate.get(Calendar.MINUTE), DateFormat.is24HourFormat(this))
            timePicker.show()
        }
    }
}