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

using DXLib.UI;
using DXLib.UI.Alert;
using DXLib.UI.Control;

using DXLib.UI.Form;
using DXLib.UI.Form.Control;
using DXLib.UI.Form.Message;

using DXLib.Utils;

namespace iStatVball3
{
	/*
	 * CRUD data entry form for a Season.
	 */
	public sealed class SeasonForm : DXForm
	{
		/* Fields */
		private readonly Team team;

		// Data import utility
		private readonly SeasonImporter importer;

		/* Methods */
		public SeasonForm( Season season, Team team ) : base( season, "season" )
		{
			this.team = team;

			header.Title = HasData ? season.Name : CreateHeader();
			imagePanel.Color = team.Color;

			/* Required */

			DateTimeOffset now = DXUtils.Now();

			// Default to current date
			DateTimeOffset start = HasData ? season.StartDate : now;

			// Start Date
			AddControl( new DXPicker
			{
				Key = "start",
				Title = "season.start",
				Date = start.LocalDateTime,
				Type = DXPicker.PickerType.Date,
				Hint = DXFormControl.HintType.Required,
				Help = "season.start"
			}, true, true );

			// End defaults 3-6 months after start
			DateTimeOffset end = HasData ? season.EndDate : start.AddMonths( team.Organization.IsClub ? 6 : 3 );

			// End Date
			AddControl( new DXPicker
			{
				Key = "end",
				Title = "season.end",
				Date = end.LocalDateTime,
				Type = DXPicker.PickerType.Date,
				Hint = DXFormControl.HintType.Date,
				Help = "season.end"
			}, true, true );

			// Name
			AddControl( new DXTextField
			{
				Key = "name",
				Title = "form.name",
				Text = season?.Name,
				MinLength = 2,
				MaxLength = 64,
				Type = DXTextField.TextType.CapitalizeWords,
				Hint = DXFormControl.HintType.RequiredMin,
				Help = "season.name"
			}, true, true );

			/* Optional */

			// Description
			AddControl( new DXTextField
			{
				Key = "desc",
				Title = "form.desc",
				Text = season?.Description,
				MinLength = 1,
				MaxLength = 256,
				Help = "season.desc"
			}, false, false );

			// Result
			AddControl( new DXTextField
			{
				Key = "result",
				Title = "season.result",
				Text = season?.Result,
				MaxLength = 64,
				Type = DXTextField.TextType.CapitalizeWords,
				Help = "season.result"
			}, false, false );

			// Notes
			AddControl( new DXEditorField
			{
				Key = "notes",
				Title = "form.notes",
				Text = season?.Notes,
				MaxLength = 1024,
				Help = "season.notes"
			}, false, false );

			// Emergency restore
			buttons.Custom = HasData ? "warn" : null;

			// Image
			SetImage( season?.ImageUrl );

			// Initial import button state
			UpdateHeader();

			// Create import utility
			importer = new()
			{
				Confirmed = OnImportConfirmed,
				Cancelled = OnImportCancelled
			};

			// Control initialization
			Init();
		}

		// Shows/hides custom header import button
		private void UpdateHeader()
		{
			CustomHeader = null;

			Season season = data as Season;

			// Most be new or most recent season for team
			if ( !HasData || team.IsCurrentSeason( season ) )
			{
				// Must have at least one prior season
				List<Season> seasons = team.Organization.GetSeasons( season );

				// Eligible for import
				if ( seasons.Count > 0 )
				{
					CustomHeader = "updown";
					CustomHeaderColor = DXColors.Action;
				}
			}
		}

		// Import confirmation enables Save button
		protected override bool HasChanges()
		{
			return base.HasChanges() || importer.HasChanges;
		}

		/* Event Callbacks */

		// User confirmed delete
		protected override async void OnDeleteConfirmed()
		{
			base.OnDeleteConfirmed();

			if ( data is Season season )
			{
				// Cascading delete
				await season.Delete( true );

				// Refresh UI
				Shell.Instance.HideForm();
			}
		}

		// Used confirmed cancel
		protected override void OnCancelConfirmed()
		{
			base.OnCancelConfirmed();

			Shell.Instance.HideForm();
		}

		// Used tapped save
		protected override async void OnSaveTapped()
		{
			// Connection required
			if ( !ValidateConnection() )
			{
				return;
			}

			// Retrieve fields
			DateTimeOffset start = GetDate( "start", true );
			DateTimeOffset end = GetDate( "end", true );
			string name = GetString( "name", true );

			string desc = GetString( "desc", false );
			string result = GetString( "result", false );
			string notes = GetString( "notes", false );

			// Validate unique name
			if ( !HasData || (name != (data as Season)?.Name) )
			{
				if ( team.GetSeasonByName( name ) != null )
				{
					ShowUniqueError( "season", "team" );
					return;
				}
			}

			base.OnSaveTapped();

			Season season;
			
			// Update existing object
			if ( HasData )
			{
				season = data as Season;
				
				if ( season != null )
				{
					season.StartDate = start;
					season.EndDate = end;
					season.Name = name;

					season.Description = desc;
					season.Result = result;
					season.Notes = notes;

					// Image
					await SaveImage( season );

					// Persist
					await season.Update();
				}
			}
			// Create new object
			else
			{
				season = new Season
				{
					StartDate = start,
					EndDate = end,
					Name = name,

					Description = desc,
					Result = result,
					Notes = notes,

					// Set parent
					TeamId = team.UniqueId,
					Team = team
				};

				User user = Shell.CurrentUser;
                
                // Allocate free trial or purchase to season
                season.PurchaseId = await PurchaseEngine.Allocate( user );
				
				// Valid
				if ( season.PurchaseId != null )
				{
					// Image
					await SaveImage( season );
					
					// Add to parent
					team.Seasons.Add( season );
					
					// Persist
					await season.Create();
				}
				// Error
				else
				{
					DXAlert.ShowError( "season.singular", "purchase.err.season" );
				}
			}

			// Handle any pending imports
			await importer.Import( season );

			// Refresh UI
			Shell.Instance.HideForm();
		}

		// User tapped Import header button
		protected override async void OnCustomHeaderTapped()
		{
			DXSpinner.Start();

			Season season = data as Season;

			// Must re-init each time
			await importer.Init( team, season );

			// Show import UI (anchored to header button)
			importer.Show( CustomHeaderBtn );
		}

		// User confirmed import, enable Save button
		private void OnImportConfirmed()
		{
			CustomHeaderBtn.Reset();

			UpdateSave();
		}

		// User dismissed importer dialog
		private void OnImportCancelled()
		{
			CustomHeaderBtn.Reset();
		}

		// User tapped footer button for emergency data restore
		protected override void OnCustomFooterTapped()
		{
			Season season = data as Season;
			
			// Begin restore process
			SeasonRestorer restorer = new( this, season );
			restorer.Start();
		}

		/* Dynamic Fields */

		// Called back when any underlying control value changes
		protected override void OnControlChanged( object sender, DXFormChangedMessage msg )
		{
			base.OnControlChanged( sender, msg );

			DXFormControl control = msg.Value as DXFormControl;
			
			switch ( control?.Key )
			{
				// End date must be after start date
				case "start":
				case "end":
				{
					if ( (GetControl( "start", true ) is DXPicker start) && (GetControl( "end", true ) is DXPicker end) )
					{
						end.IsValidValue = end.Date.CompareTo( start.Date ) > 0;
						end.UpdateState( true );

						// Enable/disable save button
						IsValid();
					}

					break;
				}
			}
		}
	}
}

//
