/* 
 * Copyright (c)2009-2025 DemiVision, LLC. All Rights Reserved. The information 
 * herein is the CONFIDENTIAL and PROPRIETARY information of DemiVision, LLC. 
 */

using Syncfusion.Maui.ListView;
using SelectionMode = Syncfusion.Maui.ListView.SelectionMode;

namespace DXLib.UI.Control.List;

/*
 * Simple wrapper for SfListView providing default configuration for a scrolling vertical list of items. Item cell
 * layout must be provided by a DataTemplate, and item data must be populated via an ObservableCollection.
 */
public class DXListView : SfListView
{
	/* Constants */

	// Wrapper for SF constants
	public enum SelectMode
	{
		None = SelectionMode.None,
		Single = SelectionMode.Single
	}

	/* Events */
	public Action<object> ItemSelected { get; set; }

	/* Properties */
	public double RowHeight { get => ItemSize; set => ItemSize = value; }

	// Selection mode
	public SelectMode Mode { set => SelectionMode = (SelectionMode)value; }

	/* Methods */
	public DXListView()
	{
		BackgroundColor = DXColors.Light2;

		// Vertical, fixed sized rows
		Orientation = ItemsLayoutOrientation.Vertical;
		AutoFitMode = AutoFitMode.None;
		LoadMoreOption = LoadMoreOption.None;

		ItemSize = 40;
		ItemSpacing = 0;

		// Scrollable, no swiping
		IsScrollingEnabled = true;
		ScrollBarVisibility = ScrollBarVisibility.Default;
		
		AllowSwiping = false;
		DragStartMode = DragStartMode.None;

		// Single select
		SelectionMode = SelectionMode.None;
		SelectionGesture = TouchGesture.Tap;
		SelectionBackground = DXColors.Action;

		// Listen for events
		SelectionChanging += OnSelectionChanging;
		SelectionChanged += OnSelectionChanged;
	}

	// Scrolls list so that specified index is centered in view
	public void ScrollTo( int index, bool animated = true )
	{
		ItemsLayout?.ScrollToRowIndex( index, ScrollToPosition.Center, animated );
	}
	
	// Redraws list item at specified index
	public void Refresh( int index, int range = 1 )
	{
		RefreshItem( index, (index + range - 1) );
	}

	/* Event Callbacks */

	// List item about to be selected, used to disable individual rows
	protected virtual void OnSelectionChanging( object sender, ItemSelectionChangingEventArgs args )
	{}

	// User selected item in list, callback listener
	private void OnSelectionChanged( object sender, ItemSelectionChangedEventArgs args )
	{
		if ( args.AddedItems is { Count: > 0 } )
		{
			ItemSelected?.Invoke( args.AddedItems[0] );
		}
	}
}

//
