Skip to content

Commit

Permalink
finish search for materials
Browse files Browse the repository at this point in the history
  • Loading branch information
mohamedshasho committed Aug 14, 2023
1 parent 5a67211 commit 1125b62
Show file tree
Hide file tree
Showing 16 changed files with 286 additions and 64 deletions.
111 changes: 111 additions & 0 deletions app/src/main/java/com/scholar/center/adapter/MaterialPagingAdapter.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,111 @@
package com.scholar.center.adapter

import android.graphics.Paint
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.paging.PagingDataAdapter
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.scholar.center.R
import com.scholar.center.databinding.SubjectItemBinding
import com.scholar.center.unit.Constants
import com.scholar.center.unit.applyDiscount
import com.scholar.domain.model.MaterialWithTeacher

class MaterialPagingAdapter(
diffCallback: DiffUtil.ItemCallback<MaterialWithTeacher>,
private val navigateToTeacher: ((Int) -> Unit)? = null,
private val navigateToDetails: (Int) -> Unit,
) :
PagingDataAdapter<MaterialWithTeacher, MaterialPagingAdapter.ViewHolder>(diffCallback) {

override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val binding =
SubjectItemBinding.inflate(LayoutInflater.from(parent.context), parent, false)
return ViewHolder(binding)
}


override fun onBindViewHolder(holder: ViewHolder, position: Int) {
val item = getItem(position)

if (item != null) {


holder.binding.materialSubjectText.text = item.material.title
val context = holder.itemView.context
if (item.teacher.name != null) {
holder.binding.materialSubjectTeacherText.text = item.teacher.name
} else {
holder.binding.materialSubjectTeacherText.visibility = View.GONE
holder.binding.materialSubjectTeacherImage.visibility = View.GONE
}

holder.binding.materialSubjectNumberHoursText.text =
context.getString(R.string.hour, item.material.hoursNumberOfWeek)

if (item.material.price != null && item.material.price != 0) {
if (item.material.discount != null && item.material.discount != 0) {
holder.binding.materialSubjectDiscountText.text = context.getString(
R.string.price_only, item.material.price
)
holder.binding.materialSubjectDiscountText.paintFlags =
holder.binding.materialSubjectDiscountText.paintFlags or Paint.STRIKE_THRU_TEXT_FLAG
val discountedPrice =
item.material.price?.applyDiscount(item.material.discount ?: 0)

holder.binding.materialSubjectPriceText.text = context.getString(
R.string.syr, discountedPrice
)
} else {
holder.binding.materialSubjectDiscountText.visibility = View.GONE
holder.binding.materialSubjectPriceText.text = context.getString(
R.string.syr, item.material.price
)
}

} else {
holder.binding.materialSubjectPriceText.visibility = View.GONE
}
holder.binding.materialSubjectStarText.text = item.totalRate.toString()

item.teacher.image?.let { image ->
Glide.with(holder.itemView)
.load("${Constants.BASE_URL}${image}")
.into(holder.binding.materialSubjectTeacherImage)
}

holder.itemView.setOnClickListener {
navigateToDetails(item.material.id)
}
holder.binding.materialSubjectTeacherText.setOnClickListener {
item.teacher.teacherId?.let { navigateToTeacher?.invoke(it) }
}
holder.binding.materialSubjectTeacherImage.setOnClickListener {
item.teacher.teacherId?.let { navigateToTeacher?.invoke(it) }
}
}
}

class ViewHolder(val binding: SubjectItemBinding) :
RecyclerView.ViewHolder(binding.root)
}

object MaterialsComparator : DiffUtil.ItemCallback<MaterialWithTeacher>() {
override fun areItemsTheSame(
oldItem: MaterialWithTeacher,
newItem: MaterialWithTeacher,
): Boolean {
// Id is unique.
return oldItem == newItem
}

override fun areContentsTheSame(
oldItem: MaterialWithTeacher,
newItem: MaterialWithTeacher,
): Boolean {
return oldItem.material.id == newItem.material.id
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import androidx.recyclerview.widget.LinearLayoutManager
import com.scholar.center.R
import com.scholar.center.adapter.CardClassITemAdapter
import com.scholar.center.databinding.FragmentClassesBinding
import com.scholar.center.unit.Constants.STAGE_ID_KEY
import com.scholar.domain.model.ClassRoom
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.launch
Expand All @@ -27,8 +28,11 @@ class ClassesFragment : Fragment(R.layout.fragment_classes) {

val navController = findNavController()
val layout = LinearLayoutManager(context, LinearLayoutManager.VERTICAL, false)

val stageId = arguments?.getInt(STAGE_ID_KEY) ?: 0

val classAdapter = CardClassITemAdapter<ClassRoom> { id ->
navController.navigate(ClassesFragmentDirections.actionClassesToClassGroup(classId = id))
navController.navigate(ClassesFragmentDirections.actionClassesToMaterials(stageId= stageId, classroomId = id))
}

binding.classesRecyclerView.run {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,22 +32,14 @@ class ClassGroupFragment : Fragment(R.layout.fragment_class_group) {
categoryAdapter?.setItemSelected(position)
}

val materialAdapter = MaterialAdapter(
navigateToTeacher = { teacherID ->
// findNavController().navigate(MainFragmentDirections.actionMainToTeacher(teacherId = teacherID))
},
navigateToDetails = {}
)


binding.classGroupMaterialsSubjectsRecyclerView.apply {
layoutManager = LinearLayoutManager(requireContext(), LinearLayoutManager.HORIZONTAL, false)
adapter = categoryAdapter
}

binding.classGroupSubjectsRecyclerView.apply {
layoutManager = LinearLayoutManager(requireContext(), LinearLayoutManager.VERTICAL, false)
adapter = materialAdapter
}


binding.classGroupToolbarBackButton.setOnClickListener {
findNavController().popBackStack()
Expand Down
10 changes: 5 additions & 5 deletions app/src/main/java/com/scholar/center/ui/home/HomeVM.kt
Original file line number Diff line number Diff line change
Expand Up @@ -52,16 +52,16 @@ class HomeVM @Inject constructor(
private fun fetchData() {
viewModelScope.launch {
_loading.value = true
val categories = async {
categoryUseCase()
launch {
categoryUseCase().collect {
_categories.value = it
}
}
launch {
materialRepository.getSomeMaterials().collect{materials->
materialRepository.getSomeMaterials().collect { materials ->
_materials.value = materials
}
}

_categories.value = categories.await()
_loading.value = false
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,8 @@ import androidx.navigation.fragment.findNavController
import androidx.recyclerview.widget.LinearLayoutManager
import com.scholar.center.R
import com.scholar.center.adapter.MaterialAdapter
import com.scholar.center.adapter.MaterialPagingAdapter
import com.scholar.center.adapter.MaterialsComparator
import com.scholar.center.databinding.FragmentMaterialsBinding
import com.scholar.center.model.UiState
import com.scholar.center.ui.dialogs.MaterialFilterDialog
Expand Down Expand Up @@ -74,7 +76,7 @@ class MaterialsFragment : Fragment(R.layout.fragment_materials), MenuProvider {

search.setOnQueryTextListener(object : SearchView.OnQueryTextListener {
override fun onQueryTextSubmit(newText: String?): Boolean {
Toast.makeText(requireContext(), newText, Toast.LENGTH_SHORT).show()
viewModel.search(newText)
view?.closeKeyboard(activity)
return true
}
Expand Down Expand Up @@ -114,7 +116,8 @@ class MaterialsFragment : Fragment(R.layout.fragment_materials), MenuProvider {
val binding = FragmentMaterialsBinding.bind(view)


val subjectsAdapter = MaterialAdapter(
val materialsAdapter = MaterialPagingAdapter(
diffCallback = MaterialsComparator,
navigateToTeacher = { teacherID ->
navController.navigate(
MaterialsFragmentDirections.actionMaterialsToTeacher(
Expand All @@ -134,7 +137,7 @@ class MaterialsFragment : Fragment(R.layout.fragment_materials), MenuProvider {
binding.subjectsRecyclerView.run {
layoutManager =
LinearLayoutManager(requireContext(), LinearLayoutManager.VERTICAL, false)
adapter = subjectsAdapter
adapter = materialsAdapter
}

// binding.subjectsToolbarBackButton.setOnClickListener {
Expand All @@ -147,9 +150,9 @@ class MaterialsFragment : Fragment(R.layout.fragment_materials), MenuProvider {
}
viewLifecycleOwner.lifecycleScope.launch {
repeatOnLifecycle(Lifecycle.State.CREATED) {
// viewModel.materials.collectLatest { materials ->
// subjectsAdapter.setList(materials)
// }
viewModel.materials.collectLatest { materials ->
materialsAdapter.submitData(materials)
}
}
}
}
Expand Down
45 changes: 34 additions & 11 deletions app/src/main/java/com/scholar/center/ui/materials/MaterialsVM.kt
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@ package com.scholar.center.ui.materials
import androidx.lifecycle.SavedStateHandle
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import androidx.paging.PagingData
import androidx.paging.cachedIn
import com.scholar.center.unit.Constants.CATEGORY_ID_KEY
import com.scholar.center.unit.Constants.CLASSROOM_ID_KEY
import com.scholar.center.unit.Constants.STAGE_ID_KEY
Expand All @@ -27,14 +29,14 @@ class MaterialsVM @Inject constructor(
private val categoryUseCase: CategoryUseCase,
private val stageUseCase: StageUseCase,
private val subjectUseCase: SubjectUseCase,
private val materialRepository: Lazy<MaterialRepository>,
private val materialRepository: MaterialRepository,
) : ViewModel() {

val categoryId = savedStateHandle.get<Int>(CATEGORY_ID_KEY)
val stageId = savedStateHandle.get<Int>(STAGE_ID_KEY)
val classRoomId = savedStateHandle.get<Int>(CLASSROOM_ID_KEY)
private val categoryId = savedStateHandle.get<Int>(CATEGORY_ID_KEY)
private val stageId = savedStateHandle.get<Int>(STAGE_ID_KEY)
private val classRoomId = savedStateHandle.get<Int>(CLASSROOM_ID_KEY)

private val _materials = MutableStateFlow<List<Material>>(emptyList())
private val _materials = MutableStateFlow<PagingData<MaterialWithTeacher>>(PagingData.empty())
val materials = _materials.asStateFlow()

private val _categories = MutableStateFlow<List<Category>>(emptyList())
Expand All @@ -52,9 +54,9 @@ class MaterialsVM @Inject constructor(
private val _loading = MutableStateFlow(false)
val loading = _loading.asStateFlow()

var selectedStage = 0
var selectedClassRoom = 0
var selectedCategory = 0
var selectedStage = stageId ?: 0
var selectedClassRoom = classRoomId ?: 0
var selectedCategory = categoryId ?: 0
var selectedSubject = 0

init {
Expand All @@ -67,21 +69,28 @@ class MaterialsVM @Inject constructor(

private fun getData() {
viewModelScope.launch {
launch {
categoryUseCase().collect {
_categories.value = it
}
}
_stages.value = stageUseCase()
_classrooms.value = classRoomRepository.observeClassesRooms().first()
_categories.value = categoryUseCase()

_subjects.value = subjectUseCase()


}
}

private fun getMaterials() {
viewModelScope.launch {
_loading.value = true
when (val result = materialRepository.get().getMaterialsFromNetwork()) {
when (val result = materialRepository.getMaterialsFromNetwork()) {
is Resource.Success -> {
_loading.value = false
result.data?.let { list ->
_materials.value = list

}
}
is Resource.Error -> {
Expand All @@ -90,4 +99,18 @@ class MaterialsVM @Inject constructor(
}
}
}

fun search(key: String?) {
if (key.isNullOrEmpty()) return

viewModelScope.launch {
materialRepository.searchForMaterialFromNetwork(key)
.cachedIn(viewModelScope)
.collect { pagingData ->
_materials.value = pagingData
}
}


}
}
Original file line number Diff line number Diff line change
Expand Up @@ -106,7 +106,6 @@ class MaterialDetailFragment : Fragment(R.layout.fragment_material_detail) {

loadingDialog.dismiss()


binding.materialPriceButton.setOnClickListener {
if (material.price == null || material.price == 0) {
// navigate to show
Expand Down
28 changes: 6 additions & 22 deletions app/src/main/res/navigation/root_nav_graph.xml
Original file line number Diff line number Diff line change
Expand Up @@ -185,32 +185,16 @@
android:label="ClassesFragment"
tools:layout="@layout/fragment_classes">
<action
android:id="@+id/action_classes_to_classGroup"
app:destination="@id/classGroupFragment"
app:enterAnim="@anim/slide_in_right"
app:exitAnim="@anim/slide_out_left"
app:popEnterAnim="@anim/slide_in_left"
app:popExitAnim="@anim/slide_out_right">
<argument
android:name="class_id"
app:argType="integer" />
</action>
</fragment>
<fragment
android:id="@+id/classGroupFragment"
android:name="com.scholar.center.ui.classgroup.ClassGroupFragment"
android:label="fragment_class_group"
tools:layout="@layout/fragment_class_group">
<action
android:id="@+id/action_classesGroup_to_material"
app:destination="@id/materialDetailFragment"
android:id="@+id/action_classes_to_materials"
app:destination="@id/materialsFragment"
app:enterAnim="@anim/slide_in_right"
app:exitAnim="@anim/slide_out_left"
app:popEnterAnim="@anim/slide_in_left"
app:popExitAnim="@anim/slide_out_right">
<argument
android:name="material_id"
app:argType="integer" />
<argument android:name="classroom_id"
app:argType="integer"/>
<argument android:name="stage_id"
app:argType="integer"/>
</action>
</fragment>

Expand Down
Loading

0 comments on commit 1125b62

Please sign in to comment.