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

using Plugin.Firebase.Firestore;

using DXLib.UI.Form;
using DXLib.UI.Alert;
using DXLib.UI.Layout;
using DXLib.UI.Container;

using DXLib.Data;
using DXLib.Utils;

namespace iStatVball3;

/*
 * Implements a popup for editing play-by-play stats for an individual stat. The popup is launched from a LogView. The
 * popup contains a header showing the currently selected team/action/result, a scrollable list of roster players, and
 * then flyouts for selecting rating/modifier/selector/fault.
 */
public class EditLogPopup : EditLogController
{
	/* Fields */
	private readonly DXGridLayout layout;
	private readonly DXFormButtons buttons;

	// Modal
	private DXPopup popup;

	// Header/roster/flyouts
	private readonly EditLogView view;

	// State control
	private LogEvent currentEvent;

	private bool hasChange;
	private bool hasSelectorChange;

	// External refs
	private readonly LogDrawer parent;
	private Set logSet;

	/* Methods */
	public EditLogPopup( LogDrawer parent )
	{
		this.parent = parent;

		bool tablet = DXDevice.IsTablet;

		// Underlying layout
		layout = new DXGridLayout
		{
			Padding = 0,
			RowSpacing = 0,
			ColumnSpacing = 0
		};

		// Header/roster/flyouts
		view = new EditLogView( this );

		// Save/cancel buttons
		buttons = new DXFormButtons( false, false )
		{
			SaveEnabled = false,

			SaveTapped = OnSaveTapped,
			CancelTapped = OnCancelTapped,
			DeleteTapped = OnDeleteTapped
		};

		// 2 rows
		layout.AddStarRow();						// 0: view
		layout.AddFixedRow( tablet ? 68 : 48 );		// 1: buttons

		// Add components
		layout.Add( view, 0, 0 );
		layout.Add( buttons, 0, 1 );
	}

	// Post construction initialization
	public void Init( Set set )
	{
		logSet = set;

		view.Init( set );
	}

	// Shows editing popup populated with specified event
	public void Show( LogEvent evt )
	{
		currentEvent = evt;

		Stat stat = evt.Stat;

		// Populate
		view.SetStat( stat );
		view.UpdateLayout();

		bool legacyAssist = logSet.Legacy && (stat.Result == Stats.AssistKey);

		// ONLY Legacy AutoAssist events can be deleted
		buttons.DeleteEnabled = legacyAssist;
		buttons.DeleteVisible = legacyAssist;

		// Launch modal popup
		popup = new DXPopup( layout )
		{
			IsModal = true,

			ViewWidth = 600,
			ViewHeight = 600
		};

		popup.Show();
	}

	// Indicates change was made in roster or flyouts
	private void HandleChange()
	{
		hasChange = true;
		buttons.SaveEnabled = (!logSet.IsSample || Shell.CurrentUser.IsAdmin);
	}

	/* Event Callbacks */

	// User selected player(s) from roster
	public void OnPlayerSelected( Player player )
	{
		bool multiBlock = (view.Players.Count > 1);

		// Multi-block not eligible for modifiers
		view.SetModifiers( currentEvent.Stat, multiBlock );

		HandleChange();
	}

	// User selected item from rating/modifier/selector flyout
	public void OnFlyoutSelected( FlyoutBar.FlyoutType type, int index )
	{
		HandleChange();

		// Selector requires special handling
		if ( type == FlyoutBar.FlyoutType.Selector )
		{
			hasSelectorChange = true;
		}
	}

	// User selected fault from flyout
	public void OnFaultSelected()
	{
		HandleChange();
	}

	// User saving changes
	private async void OnSaveTapped()
	{
		Stat stat = currentEvent.Stat;

		// Update roster selection(s)
		stat.SetPlayers( view.Players, logSet.Lineup1 );

		// Update flyouts
		stat.Rating = view.Rating;
		stat.Modifier = stat.IsMultiBlock ? null : view.Modifier;
		stat.Selector = view.Selector;

		// Update fault flyout
		stat.Fault = view.Fault;

		// May need to update block solo/assist
		EditLogView.UpdateBlockResult( stat );

		// Persist
		await stat.Update();

		// Selector change updates subsequent event
		if ( hasSelectorChange )
		{
			LogEvent nextEvent = parent.GetNextEvent( currentEvent );
			Stat nextStat = nextEvent.Stat;

			// Update subsequent
			EditLogView.UpdateNextEvent( currentEvent, nextEvent );

			// Persist
			await nextStat.Update();

			// Update UI
			parent.Modify( nextStat );
			parent.Refresh( nextEvent );
		}

		// Update UI
		parent.Modify( stat );
		parent.Refresh( currentEvent );

		parent.Deselect();
		popup.Hide();
	}

	// User cancelling editing, confirm if discarding changes
	private void OnCancelTapped()
	{
		// Warn if changes will be lost
		if ( hasChange )
		{
			DXAlert.ShowNegativeCancel( "form.cancel.title", "form.cancel.msg", "form.discard", OnCancelConfirmed );
		}
		else
		{
			OnCancelConfirmed();
		}
	}

	// User confirmed cancel, close UI
	private void OnCancelConfirmed()
	{
		parent.Deselect();
		popup.Hide();
	}

	// User deleting Legacy AutoAssist
	private async void OnDeleteTapped()
	{
		Stat stat = currentEvent.Stat;

		// Remove assist from log list
		parent.Remove( stat );
		parent.Refresh();

		IWriteBatch batch = DXData.StartBatch();

		// Delete from db (MUST be batched)
		stat.Delete( batch, true );

		await DXData.CommitBatch( batch );

		popup.Hide();
	}
}

//
