package net.pokeranalytics.android.ui.helpers

import android.graphics.Canvas
import android.view.View
import androidx.core.view.isVisible
import androidx.recyclerview.widget.ItemTouchHelper
import androidx.recyclerview.widget.RecyclerView
import net.pokeranalytics.android.R
import net.pokeranalytics.android.ui.adapter.RowRepresentableAdapter

/**
 * Swipe to delete callback
 */
class SwipeToDeleteCallback(var adapter: RowRepresentableAdapter, var onDelete: ((position: Int) -> Unit)? = null) :
	ItemTouchHelper.SimpleCallback(ItemTouchHelper.ACTION_STATE_IDLE, ItemTouchHelper.START or ItemTouchHelper.END) {

	override fun onMove(recyclerView: RecyclerView, viewHolder: RecyclerView.ViewHolder, target: RecyclerView.ViewHolder): Boolean {
		return false
	}

	override fun onSwiped(viewHolder: RecyclerView.ViewHolder, direction: Int) {
		val position = viewHolder.adapterPosition
		onDelete?.invoke(position)
	}

	override fun onChildDraw(
		c: Canvas, recyclerView: RecyclerView, viewHolder: RecyclerView.ViewHolder,
		dX: Float, dY: Float, actionState: Int, isCurrentlyActive: Boolean
	) {
		val foregroundView = viewHolder.itemView.findViewById<View?>(net.pokeranalytics.android.R.id.foreground)
		val backgroundView = viewHolder.itemView.findViewById<View?>(net.pokeranalytics.android.R.id.background)
		foregroundView?.let {
			getDefaultUIUtil().onDraw(c, recyclerView, foregroundView, dX, dY, actionState, isCurrentlyActive)
			backgroundView?.findViewById<View?>(R.id.leftIcon)?.isVisible = dX > 0
			backgroundView?.findViewById<View?>(R.id.rightIcon)?.isVisible = dX < 0
		}
	}


	override fun clearView(recyclerView: RecyclerView, viewHolder: RecyclerView.ViewHolder) {
		val foregroundView = viewHolder.itemView.findViewById<View?>(net.pokeranalytics.android.R.id.foreground)
		foregroundView?.let {
			getDefaultUIUtil().clearView(foregroundView)
		}
	}

	override fun onSelectedChanged(viewHolder: RecyclerView.ViewHolder?, actionState: Int) {
		viewHolder?.let {
			val foregroundView = viewHolder.itemView.findViewById<View?>(net.pokeranalytics.android.R.id.foreground)
			foregroundView?.let {
				getDefaultUIUtil().onSelected(foregroundView)
			}
		}
	}

	override fun onChildDrawOver(
		c: Canvas, recyclerView: RecyclerView, viewHolder: RecyclerView.ViewHolder?, dX: Float, dY: Float,
		actionState: Int, isCurrentlyActive: Boolean
	) {
		viewHolder?.let {
			val foregroundView = viewHolder.itemView.findViewById<View?>(net.pokeranalytics.android.R.id.foreground)
			foregroundView?.let {
				getDefaultUIUtil().onDrawOver(c, recyclerView, foregroundView, dX, dY, actionState, isCurrentlyActive)
			}
		}
	}

}