Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /// ViewModel
- @ExperimentalCoroutinesApi
- @SuppressLint("NullSafeMutableLiveData")
- class GroupEditViewModel
- @Inject
- constructor(
- userRepository: UserRepository,
- private val groupsRepository: GroupsRepository,
- private val contactRepository: ContactRepository,
- private val filtersRepository: FiltersRepository,
- private val dbRepository: DatabaseRepository
- ) : ViewModel() {
- val progress: Flow<Int>
- get() = _progress
- val errors: Flow<Exception>
- get() = _errors
- val watchMembersByGroup: Flow<List<MemberModel>>
- get() = _membersByGroup
- val watchParticipantsByGroup: Flow<List<Participants>>
- get() = _participantsByGroup
- val watchGroup: StateFlow<Groups?>
- get() = _group
- val startTime: StateFlow<String>
- get() = _startTime
- val endTime: StateFlow<String>
- get() = _endTime
- val filterId: StateFlow<Int>
- get() = _filterId
- val photoUri: StateFlow<String?>
- get() = _photoUri
- val saveButtonState: StateFlow<SaveButtonState>
- get() = _saveButtonState
- val editGroupState: StateFlow<GroupEditState>
- get() = _editGroupState
- private val _onUploadFilter = MutableSharedFlow<Boolean>()
- private val _onSave = MutableSharedFlow<Unit>()
- private val _groupId = MutableSharedFlow<Int>()
- private val _groupName = MutableSharedFlow<String>()
- private val _group = MutableStateFlow<Groups?>(null)
- private val _startTime = MutableStateFlow("00:00")
- private val _endTime = MutableStateFlow("23:59")
- private val _period = MutableSharedFlow<FilterModelData>()
- private val _filterType = MutableSharedFlow<Int>()
- private val _isCallEnabled = MutableSharedFlow<Boolean>()
- private val _filterId = MutableStateFlow(0)
- private val _photoUri = MutableStateFlow<String?>(null)
- private val _participants = MutableStateFlow<List<Participants>>(listOf())
- private val _saveButtonState = MutableStateFlow<SaveButtonState>(SaveButtonState.NeutralState)
- private val _editGroupState = MutableStateFlow<GroupEditState>(GroupEditState.EditStarted)
- private val _isCreateFilter = MutableSharedFlow<Boolean>()
- private val _groupModel = MutableSharedFlow<GroupsModel>()
- private val _filters = MutableSharedFlow<List<FilterModel>>()
- private val _avatarUri = MutableSharedFlow<String>()
- private val _participantsByGroup = MutableSharedFlow<List<Participants>>()
- private val _membersByGroup = MutableSharedFlow<List<MemberModel>>()
- private val userId = userRepository.userId ?: 0
- private val _errors = MutableSharedFlow<Exception>()
- private val _progress = MutableSharedFlow<Int>()
- private var counter = 0
- private var groupName: String = NO_GROUP
- private var filterType: Int = 0
- private var period: FilterModelData = FilterModelData(daily = null, table = null)
- init {
- viewModelScope.launch {
- launch {
- _groupId
- .filter { id -> id > 0 }
- .collect { fetchGroupInfo(it) }
- }
- launch {
- _groupId
- .filter { id -> id > 0 }
- .flatMapLatest { dbRepository.watchGroup(it) }
- .collect { g ->
- _group.value = g
- _membersByGroup.emit(g.groupMembers as List<MemberModel>)
- }
- }
- launch {
- _groupId
- .filter { id -> id > 0 }
- .flatMapLatest { dbRepository.watchParticipantsByGroup(it) }
- .collect { _participantsByGroup.emit(it) }
- }
- launch {
- _groupId
- .filter { id -> id > 0 }
- .combine(_groupModel) { id, gm -> id to gm }
- .collect { (id, gm) ->
- doUpdateGroupInfo(id, gm)
- }
- }
- launch {
- _groupName.collect { groupName = it.ifBlank { NO_GROUP } }
- }
- launch {
- _filterType
- .filter { id -> id > 0 }
- .distinctUntilChanged()
- .collect { filterType = it }
- }
- launch {
- _period
- .filterNotNull()
- .distinctUntilChanged()
- .collect { period = it }
- }
- launch {
- _isCreateFilter
- .filter { it }
- .combine(_isCallEnabled) { _, ic -> ic }
- .collect { ic ->
- doCreateFilter(groupName, ic, filterType, period)
- }
- }
- launch {
- _filters.collect { doUpdateFilters(it, groupName) }
- }
- launch {
- _onUploadFilter
- .collect { isE ->
- _saveButtonState.value =
- if (isE) SaveButtonState.EmptyParticipants else SaveButtonState.NeutralState
- }
- }
- launch {
- _groupId
- .filter { id -> id > 0 }
- .combine(_avatarUri) { id, a -> id to a }
- .collect { (id, a) -> doUploadGroupAvatar(id, a) }
- }
- launch {
- _onSave
- .zip(_groupId) { _, id -> id }
- .filter { id -> id > 0 }
- .combine(_filterId.filter { fId -> fId > 0 }) { id, fId -> id to fId }
- .combine(_isCallEnabled) { (id, fId), ic -> Triple(id, fId, ic) }
- .collect { (id, fId, ic) ->
- GlobalScope.launch {
- doUpdateUserFilters(
- groupId = id,
- filterId = fId,
- groupName = groupName,
- filterType = filterType,
- period = period,
- isCallEnabled = ic
- )
- }
- }
- }
- launch {
- _onSave.collect { _saveButtonState.value = SaveButtonState.PositiveState }
- }
- /**
- batch update
- */
- launch {
- _onSave
- .zip(_groupId) { _, id -> id }
- .filter { id -> id > 0 }
- .combine(_participants) { id, ps -> id to ps }
- .combine(_filterId.filter { fId -> fId > 0 }) { (id, ps), fId -> Triple(id, ps, fId) }
- .collect { (id, ps, fId) ->
- GlobalScope.launch {
- dbRepository.updateGroupFilterInfo(GroupsUpdate(id, fId))
- dbRepository.updateListContactsGroupInfo(
- ps.map { ContactsUpdate(it.userId, id) }
- )
- doUpdateUserGroupInfo(id, ps, fId, groupName)
- }
- }
- }
- }
- }
- fun onSetGroupId(groupId: Int) {
- viewModelScope.launch { _groupId.emit(groupId) }
- }
- fun onSetEditGroupState(state: GroupEditState) {
- _editGroupState.value = state
- }
- fun onTimeSelected(time: String, filter: Filter) {
- when (filter) {
- Filter.DailyStartTime -> _startTime.value = time
- Filter.DailyEndTime -> _endTime.value = time
- }
- }
- fun onSetPhotoUri(photoUri: String?) {
- _photoUri.value = photoUri
- }
- fun onSetListParticipants(participants: List<Participants>) {
- _participants.value = _participants.value + participants
- }
- fun onSetGroupName(groupName: String) {
- viewModelScope.launch { _groupName.emit(groupName) }
- }
- fun onSetFilterType(type: Int) {
- viewModelScope.launch { _filterType.emit(type) }
- }
- fun onSetPeriodData(data: FilterModelData) {
- viewModelScope.launch { _period.emit(data) }
- }
- fun onSetCanCall(isCallEnabled: Boolean) {
- viewModelScope.launch { _isCallEnabled.emit(isCallEnabled) }
- }
- fun onSetAvatarUri(uri: String) {
- viewModelScope.launch { _avatarUri.emit(uri) }
- }
- fun onSetSaveButtonState(state: SaveButtonState) {
- _saveButtonState.value = state
- }
- fun resetSaveButtonState() {
- _saveButtonState.value = SaveButtonState.NeutralState
- }
- fun onSave(isParticipantsEmpty: Boolean) {
- viewModelScope.launch {
- _onSave.emit(Unit)
- _onUploadFilter.emit(isParticipantsEmpty)
- }
- }
- private suspend fun doCreateFilter(
- groupName: String,
- isCallEnabled: Boolean,
- type: Int,
- period: FilterModelData
- ) {
- counter += 1
- _progress.emit(counter)
- when (val r = filtersRepository.setUserFilter(
- FilterData(
- groupIds = null,
- eventIds = null,
- type = type,
- filterName = groupName,
- period = period,
- canCall = isCallEnabled
- )
- )) {
- is Left -> _errors.emit(r.value)
- is Right -> {
- _filterId.value = r.value.data.id
- _filters.emit(listOf(r.value.data))
- }
- }
- counter -= 1
- _progress.emit(counter)
- }
- private suspend fun doUpdateFilters(filters: List<FilterModel>, groupName: String) {
- counter += 1
- _progress.emit(counter)
- when (val r = dbRepository.updateFilters(
- filters.map {
- Filters(
- filterId = it.id,
- userId = it.userId,
- filterName = it.filterName,
- type = it.type,
- data = it.period,
- isCanCall = it.canCall,
- //TODO remove later
- photoUri = null, //photoUri.value,
- eventIds = it.eventIds,
- groupIds = it.groupIds,
- group_name = groupName
- )
- }
- )) {
- is Left -> _errors.emit(r.value)
- is Right -> Unit
- }
- counter -= 1
- _progress.emit(counter)
- }
- private suspend fun doUpdateUserFilters(
- groupId: Int,
- filterId: Int,
- groupName: String,
- filterType: Int,
- period: FilterModelData,
- isCallEnabled: Boolean
- ) {
- counter += 1
- _progress.emit(counter)
- when (val r = filtersRepository.updateUserFilter(
- filterId, FilterData(
- groupIds = listOf(IdData(groupId)),
- eventIds = null,
- type = filterType,
- filterName = groupName,
- period = period,
- canCall = isCallEnabled
- )
- )) {
- is Left -> _errors.emit(r.value)
- is Right -> doUpdateFiltersTable(
- FiltersPartialUpdate(
- filterId = filterId,
- type = filterType,
- filterName = groupName,
- data = period,
- canCall = isCallEnabled,
- groupIds = listOf(IdData(groupId)),
- eventIds = null
- )
- )
- }
- counter -= 1
- _progress.emit(counter)
- }
- private suspend fun doUpdateFiltersTable(filter: FiltersPartialUpdate) {
- when (val r = dbRepository.partialUpdateFilters(filter)) {
- is Left -> _errors.emit(r.value)
- is Right -> Unit
- }
- }
- private suspend fun doUpdateUserGroupInfo(
- groupId: Int,
- participants: List<Participants>,
- filterId: Int,
- groupName: String
- ) {
- counter += 1
- _progress.emit(counter)
- val members: List<String?> = participants.map { it.phoneNumber }
- when (val r = groupsRepository.updateUserGroupInfo(
- groupId,
- GroupBody(filterId, groupName, members)
- )) {
- is Left -> _errors.emit(r.value)
- is Right -> _editGroupState.value = GroupEditState.EditFinished
- }
- counter -= 1
- _progress.emit(counter)
- }
- private suspend fun doUploadGroupAvatar(groupId: Int, image: String) {
- counter += 1
- _progress.emit(counter)
- when (val r = groupsRepository.uploadGroupAvatar(
- groupId, getResizedRequestBody(image, MULTIPART_AVATAR_NAME),
- )) {
- is Left -> _errors.emit(r.value)
- is Right -> r.value.data.let { doUpdateGroupAvatar(groupId, it.url) }
- }
- counter -= 1
- _progress.emit(counter)
- }
- private suspend fun doUpdateGroupAvatar(groupId: Int, avatar: String?) {
- counter += 1
- _progress.emit(counter)
- dbRepository.updateGroupAvatarInfo(GroupsAvatarUpdate(groupId, avatar))
- counter -= 1
- _progress.emit(counter)
- }
- private suspend fun fetchGroupInfo(groupId: Int) {
- counter += 1
- _progress.emit(counter)
- when (val r = groupsRepository.getUserGroupInfo(groupId)) {
- is Left -> _errors.emit(r.value)
- is Right -> {
- val fId = r.value.data.filterId
- _isCreateFilter.emit(fId <= 0)
- _filterId.emit(fId)
- _groupModel.emit(r.value.data)
- }
- }
- counter -= 1
- _progress.emit(counter)
- }
- private suspend fun doUpdateGroupInfo(groupId: Int, group: GroupsModel) {
- counter += 1
- _progress.emit(counter)
- when (val r = dbRepository.insertGroup(
- Groups(
- groupId = groupId,
- userId = userId,
- groupName = group.groupName,
- filterId = group.filterId,
- type = group.type,
- subscriptionStatus = group.subscriptionStatus,
- groupMembers = group.groupMembers,
- avatarUrl = group.avatar_url,
- isDefault = group.isDefault,
- )
- )) {
- is Left -> _errors.emit(r.value)
- is Right -> Unit
- }
- counter -= 1
- _progress.emit(counter)
- }
- fun updateContactsGroupInfo(contactsGroupBody: ContactsGroupBodyM) {
- GlobalScope.launch {
- counter += 1
- _progress.emit(counter)
- when (val r = contactRepository.updateContactsGroup(contactsGroupBody)) {
- is Left -> _errors.emit(r.value)
- is Right -> Unit
- }
- counter -= 1
- _progress.emit(counter)
- }
- }
- companion object {
- private const val NO_GROUP = "Нет группы"
- }
- }
- /// Fragment
- @ExperimentalCoroutinesApi
- class GroupEditFragment : BaseFragment(R.layout.fragment_group) {
- private val contextPhotoMenu: ContextPhotoMenuDialog by lazy { ContextPhotoMenuDialog { camera ->
- requireContext().imagePicker(
- fragment = this,
- requestCode = when (camera) {
- CameraState.CameraSelected -> 148
- CameraState.GallerySelected -> 146
- },
- isProfile = true,
- isGallery = when (camera) {
- CameraState.CameraSelected -> false
- CameraState.GallerySelected -> true
- }
- )
- } }
- private val timeDialog: TimeDialog by lazy { TimeDialog { groupEditViewModel.onTimeSelected(it, filter) } }
- private val groupEditViewModel: GroupEditViewModel by lazy { injectViewModel() }
- private val groupEditFiltersVM: GEFiltersVM by lazy { injectViewModel() }
- private val settingsViewModel: SettingsViewModel by lazy { injectViewModel() }
- private val listContactsVM: ListContactsVM by lazy { injectViewModel() }
- private val imageLoader: ImageLoaderViewModel by lazy { injectViewModel() }
- private val stateListContactsVM: StateListContactsVM by lazy { injectOneViewModelForFewFragment() }
- private var binding: FragmentGroupBinding? = null
- private var bfBinding: ButtonFiltersBinding? = null
- private var bindingCFDB: ContainerFiltersDailyBinding? = null
- private lateinit var filter: Filter
- private var groupId: Int? = null
- private var groupName: String = EMPTY_STRING
- private var isEnable = true
- private var listParticipants: List<Participants>? = null
- override fun onCreate(savedInstanceState: Bundle?) {
- super.onCreate(savedInstanceState)
- groupId = arguments?.getInt(KEY_GROUP_ID)
- groupName = arguments?.getString(KEY_GROUP_NAME).orEmpty()
- }
- override fun setupUI(v: View) {
- val pBind = ContainerParticipantsBinding.bind(v)
- val bindingImage = ContainerImageBlockBinding.bind(v)
- binding = FragmentGroupBinding.bind(v).apply {
- ContainerHeaderBlockBinding.bind(v).apply {
- headerTitleTV.text = groupName
- backButtonIV.apply {
- setImageDrawable(drawable(R.drawable.ic_close))
- setOnClickListener { navigateUp() }
- }
- saveButtonIV.setOnClickListener { onSaveButtonListener() }
- }
- with(listContactsVM) {
- progress.observe(viewLifecycleOwner) { progressBar.showProgressBar(it) }
- errors.observe(viewLifecycleOwner) {
- processingServerError(it, requireActivity()) { state ->
- when (state) {
- ServerErrorState.LogoutState -> settingsViewModel.sendLogoutRequest(requireActivity())
- else -> Unit
- }
- }
- }
- }
- lifecycleScope.launch {
- launch { imageLoader.progress.collect { progressBar.showProgressBar(it) } }
- launch {
- imageLoader.errors.collect {
- processingServerError(it, requireActivity()) { state ->
- when (state) {
- ServerErrorState.LogoutState -> settingsViewModel.sendLogoutRequest(requireActivity())
- else -> Unit
- }
- }
- }
- }
- launch { groupEditViewModel.progress.collect { progressBar.showProgressBar(it) } }
- launch {
- groupEditViewModel.errors.collect {
- processingServerError(it, requireActivity()) { state ->
- when (state) {
- ServerErrorState.LogoutState -> settingsViewModel.sendLogoutRequest(requireActivity())
- else -> Unit
- }
- }
- }
- }
- launch { groupEditFiltersVM.progress.collect { progressBar.showProgressBar(it) } }
- launch {
- groupEditFiltersVM.errors.collect {
- processingServerError(it, requireActivity()) { state ->
- when (state) {
- ServerErrorState.LogoutState -> settingsViewModel.sendLogoutRequest(requireActivity())
- else -> Unit
- }
- }
- }
- }
- }
- }
- bindingImage.apply {
- showImage(contactAvatar, R.drawable.ic_avatar_group)
- addPhotoContainer.setAllOnClickListener { checkPhotoPermission() }
- replacePhotoContainer.setAllOnClickListener { checkPhotoPermission() }
- deletePhotoContainer.setAllOnClickListener { removeProfilePhoto() }
- }
- pBind.apply {
- addParticipantsView.setOnClickListener {
- groupEditViewModel.resetSaveButtonState()
- stateListContactsVM.onSetNavEventState(LCNavState.LCAddGroupContacts)
- navigateTo(
- R.id.action_groupEditFragment_to_listContactsFragment,
- bundleOf(
- KEY_GROUP_ID to groupId
- )
- )
- }
- }
- bfBinding = ButtonFiltersBinding.bind(v).apply {
- filterCallsView.setOnClickListener { animateButton(isEnable) }
- fAllDayView.setOnClickListener { setFilterRuleListener(FilterRule.ALWAYS, it) }
- fTemplateView.setOnClickListener { setFilterRuleListener(FilterRule.TEMPLATE, it) }
- // fDailyView.setOnClickListener { setFilterRuleListener(FilterRule.DAILY, it) }
- // fTableView.setOnClickListener { setFilterRuleListener(FilterRule.SCHEDULE, it) }
- tableDetails.apply {
- setDayCell(mondayHeader, mondayDetails, R.string.day_1_full)
- setDayCell(tuesdayHeader, tuesdayDetails, R.string.day_2_full)
- setDayCell(wednesdayHeader, wednesdayDetails, R.string.day_3_full)
- setDayCell(thursdayHeader, thursdayDetails, R.string.day_4_full)
- setDayCell(fridayHeader, fridayDetails, R.string.day_5_full)
- setDayCell(saturdayHeader, saturdayDetails, R.string.day_6_full)
- setDayCell(sundayHeader, sundayDetails, R.string.day_7_full)
- }
- lifecycleScope.launch {
- launch { groupEditFiltersVM.isCanCallForView.collect { animateButton(it) } }
- launch { groupEditFiltersVM.filterRule.collect { animateDailyDetails(it) } }
- }
- }
- bindingCFDB = ContainerFiltersDailyBinding.bind(v).apply {
- dailyStartTimeV.setOnClickListener { setDailyTimeListener(Filter.DailyStartTime) }
- dailyEndTimeV.setOnClickListener { setDailyTimeListener(Filter.DailyEndTime) }
- lifecycleScope.launch {
- launch { groupEditFiltersVM.fromTime.collect { setTime(this@apply.dailyStartTimeTV, it) } }
- launch { groupEditFiltersVM.toTime.collect { setTime(this@apply.dailyEndTimeTV, it) } }
- launch { groupEditViewModel.startTime.collect { dailyStartTimeTV.text = it } }
- launch { groupEditViewModel.endTime.collect { dailyEndTimeTV.text = it } }
- }
- }
- lifecycleScope.launch {
- launch { groupEditViewModel.photoUri.collect { renderProfilePhoto(bindingImage, it) } }
- launch { groupEditViewModel.watchParticipantsByGroup.collect { listParticipants = it } }
- launch {
- groupEditViewModel
- .watchGroup
- .combine(groupEditViewModel.watchMembersByGroup) { g, ps -> g to ps }
- .collect { (g, ps) -> renderGroupInfo(bindingImage, pBind, g, ps) }
- }
- }
- }
- override fun setupObserver() {
- groupId?.let {
- groupEditViewModel.onSetGroupId(it)
- listContactsVM.onSetGroupId(it)
- }
- groupEditViewModel.onSetGroupName(groupName)
- groupEditFiltersVM.onSetGroupName(groupName)
- lifecycleScope.launch {
- launch { imageLoader.watchAvatarUrl.collect { setAvatarUrl(it) } }
- launch { listContactsVM.othersGroupId.collect { showGroupEditField(it) } }
- launch { groupEditViewModel.editGroupState.collect { onEditGroupState(it) } }
- launch { groupEditViewModel.saveButtonState.collect { saveButtonStateListener(it) } }
- launch { groupEditFiltersVM.watchFilterType.collect { groupEditViewModel.onSetFilterType(it) } }
- launch { groupEditFiltersVM.watchPeriod.collect { groupEditViewModel.onSetPeriodData(it) } }
- launch { groupEditFiltersVM.watchIsCallEnabled.collect { groupEditViewModel.onSetCanCall(it) } }
- }
- }
- override fun onDestroy() {
- super.onDestroy()
- binding = null
- bfBinding = null
- bindingCFDB = null
- }
- override fun onRequestPermissionsResult(
- requestCode: Int,
- permissions: Array<out String>,
- grantResults: IntArray
- ) {
- when (requestCode) {
- REQUEST_CODE_PHOTO -> if (grantResults.size == 3 &&
- grantResults[0] == PackageManager.PERMISSION_GRANTED &&
- grantResults[1] == PackageManager.PERMISSION_GRANTED &&
- grantResults[2] == PackageManager.PERMISSION_GRANTED
- ) contextPhotoMenu.show(requireActivity().supportFragmentManager, DIALOG_MENU_TAG)
- else processingPermissionError(requireActivity(), requireActivity().getString(R.string.photo_gallery_permission_not_granted))
- }
- }
- override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
- super.onActivityResult(requestCode, resultCode, data)
- if (resultCode == Activity.RESULT_OK) when (requestCode) {
- REQUEST_CODE_GALLERY -> processingImage(data)
- REQUEST_CODE_CAMERA -> processingImage(data)
- }
- }
- private fun showGroupEditField(id: Int) {
- groupId?.let {
- binding?.apply {
- groupNameET.isEnabled = id < it
- groupNameEditView.isVisible = id < it
- groupNameETV.isVisible = id < it
- }
- }
- }
- private fun showReplacePhotoButtons(binding: ContainerImageBlockBinding) {
- binding.apply {
- replacePhotoContainer.visibility = View.VISIBLE
- deletePhotoContainer.visibility = View.VISIBLE
- addPhotoContainer.visibility = View.GONE
- }
- }
- private fun showNewPhotoButton(binding: ContainerImageBlockBinding) {
- binding.apply {
- replacePhotoContainer.visibility = View.GONE
- deletePhotoContainer.visibility = View.INVISIBLE
- addPhotoContainer.visibility = View.VISIBLE
- }
- }
- private fun removeProfilePhoto() {
- groupEditViewModel.onSetPhotoUri(null)
- }
- private fun renderProfilePhoto(binding: ContainerImageBlockBinding, photoUri: String?) {
- binding.apply {
- photoUri?.let {
- showReplacePhotoButtons(binding)
- showImage(contactAvatar, it)
- } ?: run {
- showNewPhotoButton(binding)
- showImage(contactAvatar, R.drawable.ic_avatar_group)
- }
- }
- }
- private fun checkPhotoPermission() {
- binding?.apply {
- if (checkSelfPhotoPermission(root.context))
- requestPhotoPermission()
- else
- contextPhotoMenu.show(requireActivity().supportFragmentManager, DIALOG_MENU_TAG)
- }
- }
- private fun requestPhotoPermission() {
- if (getPhotoPermissionStatus(requireActivity()))
- requireActivity().requestPermissions(permissionPhoto(), REQUEST_CODE_PHOTO)
- else
- requireActivity().requestPermissions(permissionPhoto(), REQUEST_CODE_PHOTO)
- }
- private fun processingImage(data: Intent?) {
- data?.data?.let {
- groupEditViewModel.onSetPhotoUri(it.toString())
- uploadImage(it)
- }
- }
- private fun uploadImage(image: Uri) {
- image.path?.let { groupEditViewModel.onSetAvatarUri(it) }
- }
- private fun setAvatarUrl(url: String?) {
- groupEditViewModel.onSetPhotoUri(url)
- }
- private fun renderGroupInfo(
- b1: ContainerImageBlockBinding,
- b2: ContainerParticipantsBinding,
- group: Groups?,
- participants: List<MemberModel>
- ) {
- renderParticipantsSize(b2, participants.size)
- group?.also { g ->
- g.avatarUrl?.also { avatar -> if (avatar.isNotBlank()) renderProfilePhoto(b1, avatar) }
- g.filterId?.also { groupEditFiltersVM.onSetFilterId(it) }
- }
- }
- private fun renderParticipantsSize(bind: ContainerParticipantsBinding, size: Int) {
- bind.apply {
- participantsTitleTV.text = if (size != 0)
- resources.getQuantityString(R.plurals.participants_group_size, size, size)
- else resources.getString(R.string.fragment_group_size_zero)
- }
- }
- private fun setDayCell(b1: ContainerFiltersDayBinding, b2: ContainerFiltersDailyBinding, @StringRes day: Int) {
- b1.apply {
- dayTV.text = getString(day)
- dayView.setOnClickListener {
- dayCB.isChecked = !dayCB.isChecked
- b2.root.visibility = setViewVisibility(dayCB.isChecked)
- }
- }
- }
- private fun setTime(field: TextView, time: String) {
- bindingCFDB?.apply {
- when (field) {
- dailyStartTimeTV -> dailyStartTimeTV.text = time
- dailyEndTimeTV -> dailyEndTimeTV.text = time
- }
- }
- }
- private fun animateButton(isCanCall: Boolean) {
- isEnable = !isCanCall
- bfBinding?.apply {
- val direction = (resources.displayMetrics.widthPixels / 2) - requireContext().dpToPx(20)
- buttonView.animateSlide(if (isCanCall) -0f else direction.toFloat(), onAnimationEnd {
- bfBinding?.root?.context?.apply {
- setStateColorTV(enableTV, isCanCall)
- setStateColorTV(disableTV, !isCanCall)
- }
- })
- }
- setFilterStateListener(if (isCanCall) FilterState.ENABLE else FilterState.DISABLE)
- }
- private fun animateDailyDetails(filterRule: FilterRule) {
- groupEditFiltersVM.onCreateFilterData(filterRule)
- bindingCFDB?.apply {
- groupEditFiltersVM.onSetStartTime(dailyStartTimeTV.text.toString())
- groupEditFiltersVM.onSetEndTime(dailyEndTimeTV.text.toString())
- }
- bfBinding?.apply {
- val button: View = when (filterRule) {
- FilterRule.ALWAYS -> fAllDayView
- FilterRule.DAILY -> fDailyView
- FilterRule.SCHEDULE -> fTableView
- else -> fAllDayView
- }
- setFilterRuleListener(filterRule, button)
- }
- }
- private fun setDailyTimeListener(filter: Filter) {
- this.filter = filter
- timeDialog.show(requireActivity().supportFragmentManager, DIALOG_MENU_TAG)
- }
- private fun setFilterStateListener(state: FilterState) {
- groupEditFiltersVM.onSetFilterState(state)
- }
- private fun setFilterRuleListener(filter: FilterRule, button: View) {
- groupEditFiltersVM.onCreateFilterData(filter)
- buttonPressedListener(button)
- bfBinding?.apply {
- when (filter) {
- FilterRule.ALWAYS -> Unit
- FilterRule.DAILY -> dailyDetails.root.isVisible = true
- FilterRule.SCHEDULE -> tableDetails.root.isVisible = true
- FilterRule.TEMPLATE -> Unit
- }
- }
- }
- private fun buttonPressedListener(button: View) {
- bfBinding?.apply {
- resetButton(this)
- resetAdditionalFields(this)
- val templatesButton = listOf(fAllDayView, fTemplateView, fDailyView, fTableView)
- val templatesButtonIV = listOf(fAllDayIV, fTemplateIV, fDailyIV, fTableIV)
- val templatesButtonTV = listOf(fAllDayTV, fTemplateTV, fDailyTV, fTableTV)
- setButtonState(templatesButtonIV[templatesButton.indexOf(button)], FilterButtonState.CheckedState)
- root.context.setButtonTitle(templatesButtonTV[templatesButton.indexOf(button)], FilterButtonState.CheckedState)
- }
- }
- private fun resetButton(binding: ButtonFiltersBinding) {
- binding.apply {
- root.context.apply {
- setButtonState(fAllDayIV, FilterButtonState.NeutralState)
- setButtonTitle(fAllDayTV, FilterButtonState.NeutralState)
- setButtonState(fDailyIV, FilterButtonState.DisabledState)
- setButtonTitle(fDailyTV, FilterButtonState.DisabledState)
- setButtonState(fTableIV, FilterButtonState.DisabledState)
- setButtonTitle(fTableTV, FilterButtonState.DisabledState)
- setButtonState(fTemplateIV, FilterButtonState.NeutralState)
- setButtonTitle(fTemplateTV, FilterButtonState.NeutralState)
- }
- }
- }
- private fun resetAdditionalFields(binding: ButtonFiltersBinding) {
- binding.apply {
- dailyDetails.root.isVisible = false
- tableDetails.root.isVisible = false
- }
- }
- private fun onSaveButtonListener() {
- groupEditViewModel.onSave((listParticipants?.size ?: 0) < 1)
- }
- private fun saveButtonStateListener(buttonState: SaveButtonState) {
- when (buttonState) {
- SaveButtonState.NeutralState -> Unit
- SaveButtonState.EmptyParticipants -> requireView().showToast(getString(R.string.fragment_filter_participants_empty_error))
- SaveButtonState.PositiveState -> {
- listParticipants?.let { participants ->
- val contactsIds = mutableListOf<GroupIdModel>()
- participants.map {
- it.userId?.let { id ->
- contactsIds.add(GroupIdModel(id))
- }
- }
- groupEditViewModel.onSetListParticipants(participants.toList())
- groupEditViewModel.updateContactsGroupInfo(ContactsGroupBodyM(groupId, contactsIds))
- }
- }
- }
- groupEditViewModel.resetSaveButtonState()
- }
- private fun onEditGroupState(editGroupState: GroupEditState) {
- if (editGroupState == GroupEditState.EditFinished) navigateUp()
- }
- companion object {
- private val TAG = GroupEditFragment::class.java.simpleName
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement