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

using DXLib.UI.Alert;

using DXLib.UI.Control;
using DXLib.UI.Control.List;
using DXLib.UI.Control.Button;

using DXLib.Data;
using DXLib.Log;
using DXLib.Utils;

namespace iStatVball3;

/*
 * Main entry point for Bound integration. Provides the UI for linking with a Bound school and then for exporting match
 * stat data. The export process serializes stats and metadata for a match into Bound JSON format and then POSTs the data
 * to the API endpoint.
 */
public class VBExporter
{
	/* Properties */
	public Match Match { get; set; }
	private Team Team => Match.Season.Team;

	public DXIconButton RootBtn { get; set; }

	/* Fields */
	private string schoolId;

	/* Methods */

	// Starts Varsity Bound export process UI flow
	public void StartExport()
	{
		schoolId = Team.VarsityBoundId;

		// Must have school link
		if ( schoolId == null )
		{
			DXAlert.ShowOkCancel( "bound.title", "bound.link1", OnLink, OnDone );
		}
		// Already linked, confirm export
		else
		{
			DXAlert.ShowOkCancel( "bound.title", "bound.msg", OnExport, OnDone );
		}
	}

    // Retrieves Varsity Bound state list, displays in menu
    private async void OnLink()
    {
        DXSpinner.Start();

        List<VBState> states = null;

        // Get full state list
        try
        {
			states = await VBApi.GetStates();
		}
		catch ( Exception )
		{
            DXAlert.ShowError( "bound.title", "bound.err", OnDone );
        }

        // Error
        if ( states == null )
        {
            DXAlert.ShowError( "bound.title", "bound.err", OnDone );
        }
        // Success
        else
        {
			// Debug only
			#if DEBUG
				states.Add( new VBState { Name = "_Debug", Slug = "vb" } );
			#endif

			List<DXListMenuItem> items = new( states.Count );

            // Build menu items
            foreach ( VBState state in states )
            {
                DXListMenuItem item = new()
                {
                    Key = state.Slug,
                    Value = state.Name
                };

                items.Add( item );
            }

            // Configure menu
            DXListMenu menu = new( DXString.Get( "bound.state" ), false )
            {
				Type = DXListMenu.ListType.Text,

                ViewHeight = 275,

                ItemSelected = OnStateSelected,
				Cancelled = RootBtn.Reset
            };

            // Populate
            menu.SetItems( items, true, false );

            // Display
            menu.ListPadding = new Thickness( 5, 0 );
            menu.ShowFromView( RootBtn );
        }

        DXSpinner.Stop();
    }

    // Retrieves Varsity Bound school list, displays in menu
    private async void OnStateSelected( DXItem selected )
	{
		DXSpinner.Start();

		string state = selected.Key;

		// Get school list for state
		List<VBSchool> schools = await VBApi.GetSchools( state );

		// Error
		if ( schools == null )
		{
			DXAlert.ShowError( "bound.title", "bound.err", OnDone );
		}
		// Success
		else
		{
			List<DXListMenuItem> items = new( schools.Count );

			// Build menu items
			foreach ( VBSchool school in schools )
			{
				DXListMenuItem item = new()
				{
					Key = school.Id,
					Value = school.Name,
					SubValue = school.Mascot
				};

				items.Add( item );
			}

			// Configure menu
			DXListMenu menu = new( DXString.Get( "bound.school" ), false )
			{
				Type = DXListMenu.ListType.Image,
				Icon = "organization",

				ViewHeight = 400,

				ItemSelected = OnSchoolSelected,
                Cancelled = RootBtn.Reset
            };

			// Populate
			menu.SetItems( items, true, true );

			// Display
			menu.ListPadding = new Thickness( 5, 0 );
			menu.ShowFromView( RootBtn );

			DXSpinner.Stop();
		}
	}

	// User selected school from Varsity Bound list
	private void OnSchoolSelected( DXItem item )
	{
		schoolId = item.Key;

		DXAlert.ShowOkCancel( "bound.title", "bound.link2", item.Value, OnLinkConfirmed, OnDone );
	}

	// User confirmed school link
	private async void OnLinkConfirmed()
	{
		Team.VarsityBoundId = schoolId;

		// Persist
		await Team.Update( "VarsityBoundId", Team.VarsityBoundId );

		// Success
		DXAlert.ShowOk( "bound.title", "bound.link3", OnLinkSuccess );
	}

	// School link successful, alert user
	private void OnLinkSuccess()
	{
		DXAlert.ShowOkCancel( "bound.title", "bound.msg", OnExport, OnDone );
	}

	// User confirmed export
	private async void OnExport()
	{
		DXSpinner.Start();

		// Serialize and POST
		if ( await Export() )
		{
			DXAlert.ShowOk( "bound.title", "bound.success", OnDone );
		}
		// Error
		else
		{
			DXAlert.ShowError( "bound.title", "bound.err", OnDone );
		}
	}

	// Export cancelled or completed, reset UI
	private void OnDone()
	{
		RootBtn.Reset();

		DXSpinner.Stop();
	}

	// Serializes and POSTs match stats
	private async Task<bool> Export()
	{
		try
		{
			// Serialize into JSON export
			VBExport export = await VBSerializer.Serialize( Match );

			string boundId = Match.Season.Team.VarsityBoundId;

			// Upload to endpoint
			return await VBApi.UploadStats( boundId, export );
		}
		catch ( Exception ex )
        {
	        DXLog.Error( "bound.export", ex.Message );
			DXAlert.ShowError( "bound.title", "bound.err", OnDone );

			return false;
        }
    }
}

//
