package ta1.cis.activity

import android.app.TimePickerDialog
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.text.format.DateFormat
import android.util.Log
import android.widget.TimePicker
import android.widget.Toast
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_request_izin_bermalam.*
import kotlinx.android.synthetic.main.activity_request_izin_keluar.*
import kotlinx.android.synthetic.main.item_izin_keluar.*
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import ta1.cis.R
import ta1.cis.api.RetrofitInstance
import ta1.cis.helper.SharedPref
import ta1.cis.model.request.IKRequest
import java.text.SimpleDateFormat
import java.util.*

class RequestIzinKeluarActivity : AppCompatActivity() {
    private lateinit var sharedPref: SharedPref
    private var waktuBerangkat : String = ""
    private var waktuKembali : String = ""

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_request_izin_keluar)
        setSupportActionBar(topAppBarIK)
        supportActionBar?.setDisplayHomeAsUpEnabled(true)
        sharedPref = SharedPref(this)
        topAppBarIK.setNavigationOnClickListener {
            onBackPressed()
        }
        btn_berangkatIK.setOnClickListener {
            getDate(0);
        }
        btn_kembaliIK.setOnClickListener {
            getDate(1);
        }
        buatIk.setOnClickListener {

            if(tgl_berangkatIK.text.isNullOrBlank() || tgl_kembaliIK.text.isNullOrBlank() || keperluan_ik.text.isNullOrBlank()){
                Toast.makeText(this,"Harap mengisi field terlebih dahulu",Toast.LENGTH_LONG).show()
            }else{
                var cek = validate()
                if(cek == -1){
                    var request = IKRequest(
                        waktuBerangkat,
                        waktuKembali,
                        keperluan_ik.text.toString()
                    )
                    saveIk(request)
                }
            }

        }
    }

    private fun saveIk(request: IKRequest) {
        RetrofitInstance.instanceRetrofit.saveIK(sharedPref.getDimId().toLong(),request,"Bearer ${sharedPref.getTokenBearer()}")
            .enqueue(object : Callback<Any>{
                override fun onResponse(call: Call<Any>, response: Response<Any>) {
                    Toast.makeText(this@RequestIzinKeluarActivity,"Izin sudah di request",Toast.LENGTH_LONG).show()
                    onBackPressed()
                }

                override fun onFailure(call: Call<Any>, t: Throwable) {
                    Toast.makeText(this@RequestIzinKeluarActivity,"Ada Masalah dalam internet kamu",Toast.LENGTH_LONG).show()
                    onBackPressed()
                }
            })
    }

    fun validate() : Int{
        var cek_count = 0;
        val sdf = SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
        var date1  = sdf.parse(tgl_berangkatIK.text.toString());
        var date2 = sdf.parse(tgl_kembaliIK.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){
            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, 1);
        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_berangkatIK.setText(waktuBerangkat.toString())
                    }else{
                        waktuKembali += " ${hourOfDay}:${minute}:00"
                        tgl_kembaliIK.setText(waktuKembali.toString())
                    }
                }
            },mcurrentDate.get(Calendar.HOUR_OF_DAY), mcurrentDate.get(Calendar.MINUTE), DateFormat.is24HourFormat(this))
            timePicker.show()
        }
    }
}