package ta1.cis.activity

import android.app.TimePickerDialog
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.util.Log
import android.view.Menu
import android.view.MenuItem
import android.view.View
import android.widget.TimePicker
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.navigation.NavController
import ta1.cis.api.RetrofitInstance
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_detail_paket.*
import ta1.cis.helper.Connectivity
import ta1.cis.helper.SharedPref
import kotlinx.android.synthetic.main.activity_request_izin_bermalam.*
import kotlinx.android.synthetic.main.activity_request_izin_bermalam.topAppBar
import kotlinx.android.synthetic.main.fragment_home.*
import ta1.cis.model.request.IBRequest
import ta1.cis.model.response.ResponseSaveIB
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import ta1.cis.R
import java.text.SimpleDateFormat
import java.util.*


class RequestIzinBermalamActivity : 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_bermalam)
        setSupportActionBar(topAppBar)

        supportActionBar?.setDisplayHomeAsUpEnabled(true)
        sharedPref = SharedPref(this)
        btn_berangkat.setOnClickListener {
            getDate(0)
        }
        btn_kembali.setOnClickListener {
            getDate(1)
        }
        batal.setOnClickListener {
            onBackPressed()
        }
        buat.setOnClickListener {
            if(!tgl_berangkat.text!!.isEmpty() && !tgl_kembali.text!!.isEmpty() &&
                !keperluanIb.text!!.isEmpty() && !tujuan.text!!.isEmpty()){
                    val compare = validate()
                    if(compare == -1){
                        val request = IBRequest(
                            tgl_berangkat.text.toString(),
                            tgl_kembali.text.toString(),
                            keperluanIb.text.toString(),
                            tujuan.text.toString()
                        )
                        pb_ib.visibility = View.VISIBLE
                        saveIB(request)
                    }
            }else{
                if(waktuBerangkat.isNullOrEmpty()){
                    tgl_berangkat.error = "Data wajib diisi"
                    tgl_berangkat.requestFocus()
                }else{
                    tgl_berangkat.error = null
                }
                if(waktuKembali.isNullOrEmpty()){
                    tgl_kembali.error = "Data wajib diisi"
                    tgl_kembali.requestFocus()
                }else{
                    tgl_kembali.error = null
                }

            }
        }
        topAppBar.setNavigationOnClickListener {
            onBackPressed()
        }
    }
    fun validate() : Int{
        var cek_count = 0;
        val sdf = SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
        var date1  = sdf.parse(tgl_berangkat.text.toString());
        var date2 = sdf.parse(tgl_kembali.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;
    }

    fun saveIB(requestIb : IBRequest){
        if(Connectivity.isNetworkAvailable(this as Context)){
            val token = sharedPref.getTokenBearer();
           val userId = sharedPref.getDimId().toLong()
            RetrofitInstance.instanceRetrofit.saveIzinBermalam("Bearer $token",userId,requestIb)
                .enqueue(object : Callback<ResponseSaveIB>{
                override fun onFailure(call: Call<ResponseSaveIB>, t: Throwable) {
                    Toast.makeText(this@RequestIzinBermalamActivity,"Error : ${t.message}",Toast.LENGTH_SHORT).show()
                }
                override fun onResponse(
                    call: Call<ResponseSaveIB>,
                    response: Response<ResponseSaveIB>
                ) {
                    pb_ib.visibility = View.GONE
                    sharedPref.setStatusUpdate(2)
                    onBackPressed()
                }
            })
        }
    }

    fun getDate(id : 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 Berangkat")
            .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(id == 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(id == 0){
                        waktuBerangkat += " ${hourOfDay}:${minute}:00"
                        tgl_berangkat.setText(waktuBerangkat.toString())
                    }else{
                        waktuKembali += " ${hourOfDay}:${minute}:00"
                        tgl_kembali.setText(waktuKembali.toString())
                    }
                }
            },mcurrentDate.get(Calendar.HOUR_OF_DAY), mcurrentDate.get(Calendar.MINUTE), android.text.format.DateFormat.is24HourFormat(this))
            timePicker.show()
        }
    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
       if(item.itemId == android.R.id.home){

       }
        return super.onOptionsItemSelected(item)
    }

    override fun onCreateOptionsMenu(menu: Menu?): Boolean {
        return super.onCreateOptionsMenu(menu)
    }
}

