package app.gedama.tutorial.cruddiary.fragment
import android.app.DatePickerDialog
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.lifecycle.*
import androidx.lifecycle.Observer
import app.gedama.tutorial.cruddiary.R
import androidx.navigation.findNavController
import app.gedama.tutorial.cruddiary.data.Spinnable
import app.gedama.tutorial.cruddiary.data.Validation
import app.gedama.tutorial.cruddiary.database.CrudDiaryDatabase
import app.gedama.tutorial.cruddiary.databinding.FragmentUpdatePersonBinding
import app.gedama.tutorial.cruddiary.ui.LambdaDatePicker
import app.gedama.tutorial.cruddiary.ui.formfields.FormFieldText
import app.gedama.tutorial.cruddiary.viewmodel.UpdatePersonViewModel
import app.gedama.tutorial.cruddiary.viewmodel.UpdatePersonViewModelFactory
import com.google.android.material.snackbar.Snackbar
import java.text.DateFormat
import java.util.*
class UpdatePersonFragment: BaseFragment() {
private var _binding: FragmentUpdatePersonBinding? = null
private val binding get() = _binding!!
lateinit var viewModel: UpdatePersonViewModel
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View {
_binding = FragmentUpdatePersonBinding.inflate(inflater, container, false)
val view = binding.root
val personId = UpdatePersonFragmentArgs.fromBundle(requireArguments()).personId
val application = requireNotNull(this.activity).application
val personDao = CrudDiaryDatabase.getInstance(application).personDao
val viewModelFactory = UpdatePersonViewModelFactory(personId,personDao)
viewModel = ViewModelProvider(this, viewModelFactory)[UpdatePersonViewModel::class.java]
binding.viewModel = viewModel
binding.lifecycleOwner = viewLifecycleOwner
val fieldName = FormFieldText(
scope = lifecycleScope,
textInputLayout = binding.nameTextFieldBinding.nameLayout,
textInputEditText = binding.nameTextFieldBinding.name,
Validation.nameValidation
)
val fieldBirthday = FormFieldText(
scope = lifecycleScope,
textInputLayout = binding.birthdateTextFieldBinding.dateLayout,
textInputEditText = binding.birthdateTextFieldBinding.date,
Validation.birthdayValidation
)
val fieldGender = FormFieldText(
scope = lifecycleScope,
textInputLayout = binding.spinnerGendersBinding.spinnerInputLayoutId,
textInputEditText = binding.spinnerGendersBinding.spinnerTextId,
Validation.genderValidation
)
val formFields = listOf(fieldName,fieldBirthday,fieldGender)
initImagePicking(binding.imageAreaBinding.imageView, binding.imageAreaBinding.buttonLoadPicture,viewModel, binding.imageAreaBinding.buttonDefaultPicture)
saveToUpdateButton(binding.crudButtons.actionButton)
viewModel.navigateToList.observe(viewLifecycleOwner, Observer { navigate ->
if (navigate) {
view.findNavController()
.navigate(R.id.action_updatePersonFragment_to_personsListFragment)
viewModel.onNavigatedToList()
}
})
viewModel.allGendersAndPersonLiveData.observe(viewLifecycleOwner, Observer { (allg,pers) ->
val genderId = pers.genderId ?: 1L
val currentGender = allg.find{ it.genderId == genderId }
val currentGenderPos = allg.indexOf(currentGender)
binding.spinnerGendersBinding.spinnerId.setSelection(currentGenderPos)
} )
viewModel.person.observe(viewLifecycleOwner, Observer { item ->
if ( item.birthDate != null ) {
binding.birthdateTextFieldBinding.date.setText(DateFormat.getDateInstance(DateFormat.MEDIUM).format(item.birthDate!!))
}
setChangeImageButton(view, item.imagePath, viewModel)
setInactivityButton(item.inactive,binding.crudButtons.deactivateButton,binding.checkBoxBinding.checkBoxInactive)
})
viewModel.newBirthdate.observe(viewLifecycleOwner, Observer { item ->
binding.birthdateTextFieldBinding.date.setText(DateFormat.getDateInstance(DateFormat.MEDIUM).format(item))
})
viewModel.doValidation.observe(viewLifecycleOwner, Observer { doValidate ->
if (doValidate) {
formValidation(binding.crudButtons.actionButton, formFields, viewModel)
}
})
viewModel.insertSuccess.observe(viewLifecycleOwner, Observer { isSuccess ->
if (isSuccess != null && !isSuccess ) {
Snackbar.make(binding.crudButtons.actionButton,resources.getText(R.string.unique_person_violation),
Snackbar.LENGTH_INDEFINITE).show()
Log.d(TAG,"There was a problem when updating person data in the database ...")
}
})
@Suppress("UNCHECKED_CAST")
initMaterialSpinnerData(binding.spinnerGendersBinding.spinnerId,binding.spinnerGendersBinding.spinnerTextId,
viewModel.allGenders as LiveData<List<Spinnable>>,{ item: Spinnable -> viewModel.updateGender(item)} )
binding.birthdateTextFieldBinding.date.setOnClickListener(handleIconClick)
binding.birthdateTextFieldBinding.dateLayout.setEndIconOnClickListener(handleIconClick)
setDeleteImageButton(binding.imageAreaBinding.buttonDefaultPicture,binding.imageAreaBinding.imageView,
binding.imageAreaBinding.imageViewContainer,binding.imageAreaBinding.buttonLoadPicture, viewModel)
setDeactivateButton(binding.crudButtons.deactivateButton, { viewModel.deactivatePerson() } )
return view
}
override fun onDestroyView() {
super.onDestroyView()
_binding = null
}
private val handleIconClick = object : View.OnClickListener {
override fun onClick(v: View?) {
val picker = LambdaDatePicker(context!!, showTimePicker = false, { item: Date -> viewModel.updateBirthdate(item) })
val currentBirthdate = Calendar.getInstance()
viewModel.person.value?.birthDate?.let {
currentBirthdate.time = viewModel.person.value!!.birthDate!!
}
val datePickerDialog =
DatePickerDialog(
context!!,
picker,
currentBirthdate.get(Calendar.YEAR),
currentBirthdate.get(
Calendar.MONTH
),
currentBirthdate.get(Calendar.DAY_OF_MONTH)
)
datePickerDialog.datePicker.maxDate = Date().time
datePickerDialog.show()
}
}
}