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

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

namespace iStatVball3;

/*
 * CRUD data entry form for an Organization.
 */
public sealed class OrganizationForm : DXForm
{
	/* Fields */
	private readonly User user;

	// MaxPreps
	private MP2Interface maxPreps;

    /* Methods */
    public OrganizationForm( Organization org, User user ) : base( org, "organization" )
	{
		this.user = user;

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

        /* Required */

        // Type
        AddControl( new DXSelectorField
		{
			Key = "type",
			Title = "form.type",
			Items = "organization.type",
			SelectedItem = org?.Type,
			Hint = DXFormControl.HintType.Required,
			Help = "organization.type",
			ControlChanged = OnTypeChanged
		}, true, true );

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

		// Abbreviation
		AddControl( new DXTextField
		{
			Key = "abbreviation",
			Title = "form.abbrev",
			Text = org?.Abbreviation,
			MinLength = 1,
			MaxLength = 5,
			Type = DXTextField.TextType.AllCaps,
			Hint = DXFormControl.HintType.RequiredRange,
			Help = "organization.abbreviation"
		}, true, true );

		/* Optional */

		// Mascot
		AddControl( new DXTextField
		{
			Key = "mascot",
			Title = "organization.mascot",
			Text = org?.Mascot,
			MaxLength = 32,
			Type = DXTextField.TextType.CapitalizeWords,
			Help = "organization.mascot"
		}, false, false );

		// Location
		AddControl( new DXTextField
		{
			Key = "location",
			Title = "form.location",
			Text = org?.Location,
			MinLength = 1,
			MaxLength = 64,
			Type = DXTextField.TextType.CapitalizeWords,
			Help = "organization.location"
		}, false, false );

		// Color
		AddControl( new DXColorPickerField
		{
			Key = "color",
			Title = "organization.color",
			PickedValue = org?.ColorValue,
			DefaultColor = Organization.DefaultColor,
			AllowWhite = false,
			Help = "organization.color"
		}, false, false );

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

		// Image
		SetImage( org?.ImageUrl );

		// Control initialization
		Init();

        // May have MaxPreps link
        InitMaxPreps();
    }

    // Initializes MaxPreps related UI
    private void InitMaxPreps()
	{
        if ( data is Organization org )
        {
	        // Check permissions
	        if ( Organization.CanCreate( Shell.CurrentUser ) && (!HasData || !org.IsSample) )
	        {
		        if ( GetControl( "type", true ) is DXSelectorField type )
		        {
			        // High school has MaxPreps link
			        bool highSchool = Equals( type.SelectedItem, "high" );

			        // Create selector/remover
			        maxPreps = new MP2Interface()
			        {
				        Form = this,
				        School = org.MaxPreps,
				        IsHighSchool = highSchool
			        };

			        // Show link button
			        maxPreps.UpdateHeader();
		        }
	        }
        }
	}

    /* Abstracts */

    // Overrides to include MaxPreps
    protected override bool HasChanges()
    {
        return base.HasChanges() || (maxPreps is { HasChanges: true });
    }

    /* Event Callbacks */

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

		// Cascading delete
		if ( data is Organization organization )
		{
			await organization.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
		string type = GetString( "type", true );
		string name = GetString( "name", true );
		string abbreviation = GetString( "abbreviation", true );

		string mascot = GetString( "mascot", false );
		string location = GetString( "location", false );
		long color = GetColor( "color", false );
		string notes = GetString( "notes", false );

		MP2School school = maxPreps?.School;

		// Validate unique name
		if ( !HasData || (name != (data as Organization)!.Name) )
		{
			if ( user.GetOrganizationByName( name ) != null )
			{
				ShowUniqueError( "organization", "user" );
				return;
			}
		}

		base.OnSaveTapped();

		// Update existing object
		if ( HasData )
		{
			if ( data is Organization org )
			{
				org.Type = type;
				org.Name = name;
				org.Abbreviation = abbreviation;

				org.Mascot = mascot;
				org.Location = location;
				org.ColorValue = color;
				org.Notes = notes;

				org.MaxPreps = school;

				// Image
				await SaveImage( org );

				// Persist
				await org.Update();
			}
		}
		// Create new object
		else
		{
			Organization org = new()
			{
				Type = type,
				Name = name,
				Abbreviation = abbreviation,

				Mascot = mascot,
				Location = location,
				ColorValue = color,
				Notes = notes,

				MaxPreps = school,

				// Set parent
				UserId = user.UniqueId,
				User = user
			};

			// Image
			await SaveImage( org );

			// Add to parent
			user.Organizations.Add( org );

			// Persist
			await org.Create();
		}

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

	// User tapped MaxPreps link button
	protected override async void OnCustomHeaderTapped()
	{
		await maxPreps.Show();
	}

    /* Dynamic Fields */

	// User selected organization type
    private void OnTypeChanged()
	{
		// Clear any previous selection
        if ( data is Organization org )
        {
            org.MaxPreps = null;
        }

        InitMaxPreps();
		UpdateSave();
	}
}

//
