package mx.trackermap.TrackerMap.android.devices import android.graphics.Color import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.recyclerview.widget.RecyclerView import mx.trackermap.TrackerMap.android.R import mx.trackermap.TrackerMap.android.databinding.UnitItemBinding import mx.trackermap.TrackerMap.utils.Formatter import mx.trackermap.TrackerMap.client.models.UnitInformation enum class Action { CLICK, DETAILS, REPORTS, COMMANDS } typealias ActionCallback = (unit: UnitInformation, action: Action) -> Unit class DevicesAdapter( private val units: List, private val actionCallback: ActionCallback? ) : RecyclerView.Adapter() { override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { val binding = UnitItemBinding.inflate(LayoutInflater.from(parent.context), parent, false) return ViewHolder(binding) } override fun onBindViewHolder(holder: ViewHolder, position: Int) { val unit = units[position] val context = holder.itemView.context holder.binding.apply { unit.position?.let { position -> /* Status icon */ position.speed?.let { speed -> if (speed >= 2) { statusIcon.setColorFilter(Color.GREEN) } else { statusIcon.setColorFilter(Color.RED) } } ?: run { statusIcon.setColorFilter(Color.GRAY) } /* Engine stop */ val attributes = position.attributes if (attributes["out1"].toString() == "null") { engineStopIcon.visibility = View.GONE } else { engineStopIcon.visibility = View.VISIBLE engineStopIcon.setImageResource( when (attributes["out1"].toString()) { "true" -> R.drawable.ic_baseline_lock_24 "false" -> R.drawable.ic_baseline_lock_open_24 else -> R.drawable.ic_baseline_lock_open_24 } ) engineStopIcon.contentDescription = when (attributes["out1"].toString()) { "true" -> context.getString(R.string.unit_lock_on) "false" -> context.getString(R.string.unit_lock_off) else -> context.getString(R.string.unit_lock_on) } } } unitName.text = unit.device.name driverName.text = unit.device.contact unitSpeed.text = context.getString(R.string.unit_speed_format, unit.position?.speed?.toInt() ?: 0) lastAddress.text = unit.position?.address unit.position?.fixTime?.let { lastDate.text = Formatter.formatDate(it) } actionCallback?.let { callback -> unitCard.setOnClickListener { callback(unit, Action.CLICK) } detailsButton.setOnClickListener { callback(unit, Action.DETAILS) } reportsButton.setOnClickListener { callback(unit, Action.REPORTS) } commandsButton.setOnClickListener { callback(unit, Action.COMMANDS) } } } } override fun getItemCount(): Int = units.size inner class ViewHolder(val binding: UnitItemBinding) : RecyclerView.ViewHolder(binding.root) }