/* 
 * 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.Layout;
using DXLib.UI.Control;
using DXLib.UI.Container;

using DXLib.Email;
using DXLib.Data;
using DXLib.Utils;

namespace iStatVball3;

/*
 * Overall UI shell for Set editing. Includes a segment bar to toggle between forms for editing set info, play-by-play
 * (log), and tally stats.
 */
public class SetEditForm : DXContent
{
	/* Constants */
	private const string InfoKey = "info";
	private const string LogKey = "log";
	private const string TallyKey = "tally";
	
	/* Fields */
	private readonly DXSegmentBar segmentBar;
	private readonly DXGridLayout panelLayout;

	// Set info, log, tally
	private SetForm setForm;
	private EditLogForm logForm;
	private EditTallyForm tallyForm;

	private string activeKey;
	
    // Email export
    private ReportExporter exporter;

    // Set being edited
    private Set editSet;
    
	/* Methods */
	public SetEditForm()
	{
		BackgroundColor = DXColors.Dark1;
		
		// Layout
		DXGridLayout layout = new()
		{
			BackgroundColor = DXColors.Dark1,

			Padding = 0,
			RowSpacing = 0,
			ColumnSpacing = 0,
			
			Horizontal = LayoutOptions.Fill,
			Vertical = LayoutOptions.Fill,
			
			// REQUIRED
			IgnoreSafeArea = true
		};

		// 3 rows
		layout.AddFixedRow( 1 );        // 0: border
		layout.AddFixedRow( 50 );       // 1: segment bar
		layout.AddStarRow();            // 2: form

		// Info/log/tally selector
		segmentBar = new DXSegmentBar()
		{
			Mode = DXSegmentBar.SegmentMode.Text,

			FillColor = DXColors.Dark3,
			TextColor = DXColors.Light4,
			SelectColor = DXColors.Light4,

			SegmentWd = 120,
			SegmentHt = 40,
			SegmentFontSize = 15,

			Horizontal = LayoutOptions.Center,
			Vertical = LayoutOptions.Center,

			Selected = OnSelected
		};

		segmentBar.Init();

		// Add segments (text set later)
		segmentBar.AddSegment( InfoKey );
		segmentBar.AddSegment( LogKey );
		segmentBar.AddSegment( TallyKey );
		
		layout.Fill( DXColors.Dark3, 0, 1 );
		layout.Add( segmentBar, 0, 1 );

		// Used to switch panel content
		panelLayout = new DXGridLayout
		{
			Horizontal = LayoutOptions.Fill,
			Vertical = LayoutOptions.Fill,
			
			IsClippedToBounds = true,
			IgnoreSafeArea = true
		};
		
		layout.Add( panelLayout, 0, 2 );

		Content = layout;
	}
	
	// Post construction initialization
	public void Init( Set set )
	{
		editSet = set;

		// Editing not always valid
		segmentBar.Disable( LogKey, (set.Match.IsPaper || set.IsNew) );
		segmentBar.Disable( TallyKey, !set.IsEnded );

		// Create set info form
		setForm = new SetForm( set, set.Match );

		// Always start with set info
		segmentBar.SelectKey( InfoKey );
		OnSelected( InfoKey );
	}

	// Used internally to switch panel content
	private void AddContent( string key, DXContent content )
	{
		activeKey = key;
		
		panelLayout.ClearAll();
		panelLayout.Add( content );
	}
	
	/* Event Callbacks */

	// User toggle segment bar selection
	private async void OnSelected( string key )
	{
		DXSpinner.Start();
		
		ToolBar toolBar = Shell.Instance.ToolBar;

		// Export only for PbP
		toolBar.RemoveCustom( 1 );

        // Set info
        if ( key == InfoKey )
		{
			AddContent( InfoKey, setForm );
		}
		else
		{
			// Stat editing requires network
			if ( DXData.HasConnection() )
			{
				switch ( key )
				{
					// Play-by-Play
					case LogKey:
					{
						// Create PbP log form
						logForm = new EditLogForm();
						await logForm.Init( editSet );

						AddContent( LogKey, logForm );

						// Eligible for PDF export
						toolBar.AddCustom( 1, "export", "export.item" );
						toolBar.Custom1Tapped = OnExportTapped;
						break;
					}
					// Tally stats
					case TallyKey:
					{
						Match match = editSet.Match;

						// Create tally edit form
						tallyForm = new EditTallyForm( !match.IsPaper );
						await tallyForm.Init( editSet, match.Color );

						AddContent( TallyKey, tallyForm );
						break;
					}
				}
			}
			else
			{
				DXAlert.ShowNetworkError( "net.err.edit", () =>
				{
					segmentBar.SelectedKey = InfoKey;
					AddContent( InfoKey, setForm );

					UpdateLayout();
				});
			}
		}

		UpdateLayout();

		DXSpinner.Stop();
	}

	// User tapped PbP export
	private void OnExportTapped()
    {
        if ( DXData.HasConnection() )
        {
             // Check user setting
             switch ( Shell.Settings.ExportEmail )
             {
                 // Local app (Apple/Google Mail)
                 case Settings.EmailLocal:
                 {
   					string subject = DXString.Get( "log.subject" );
     
                     // Send immediately via native app
                     OnExport( new ReportExportConfig()
                     {
                         IsLocal = true,
                         Subject = subject
                     });
     
                     break;
                 }
                 // Cloud provider (SendGrid)
                 case Settings.EmailCloud:
                 {
                     Season season = editSet.Match.Season;
     
                     // Show single/group email popup
                     exporter = new ReportExporter( season )
                     {
                         Completed = OnExport,
                         Cancelled = OnDone
                     };
     
                     exporter.Show( true );
                     break;
                 }
             }
        }
        // Connection required
        else
        {
            DXAlert.ShowNetworkError( "net.err.log" );
        }
    }
	
     // User confirmed export
     private async void OnExport( ReportExportConfig exportConfig )
     {
         DXSpinner.Start();
         
         string title = DXString.Get( "log.title" );
  
         // Create PDF with all PbP stats, send as email attachment
         DXEmail.Result result = await LogExporter.Export( new ExportConfig
         { 
			IsLocal = exportConfig.IsLocal,
			
			FromAddress = exportConfig.FromAddress,
			ToAddresses = exportConfig.ToAddresses,
			ToNames = exportConfig.ToNames,
			
			Subject = exportConfig.Subject,
			Title = title,
			
			Stats = editSet.StatCache,
  
			DataConfig = new DataConfig
			{
				Scope = DataConfig.SetScope,
				ScopeObject = editSet
			}
         });
    
         switch ( result )
         {
             // Success
             case DXEmail.Result.Success:
             {
                 DXAlert.ShowOk( "export.title", "export.success", title, OnDone );
                 break;
             }
             // Email not supported
             case DXEmail.Result.ErrorUnsupported:
             {
                 DXAlert.ShowError( "export.title", "export.err.support", OnDone );
                 break;
             }
             // Other error
             case DXEmail.Result.Error:
             default:
             {
                 DXAlert.ShowError( "export.item", "export.err", OnDone );
                 break;
             }
         }
     }

    // Export successful
    private void OnDone()
    {
        DXSpinner.Stop();

        // Reset
        exporter?.Hide();
        exporter = null;

        Shell.Instance.ToolBar.ResetCustom();
    }

    /* Layout */

    // Redraws current form
    public override void UpdateLayout( LayoutType type )
	{
		// Update children
		if ( activeKey != null )
		{
			bool abbrev = (type == LayoutType.MobilePortrait);

			// Dynamically update segment titles
			segmentBar.SetResource( InfoKey, (abbrev ? "set.info.abbrev" : "set.info") );
			segmentBar.SetResource( LogKey, (abbrev ? "set.log.abbrev" : "set.log") );
			segmentBar.SetResource( TallyKey, (abbrev ? "set.tally.abbrev" : "set.tally") );

			// Show current segment
			switch ( activeKey )
			{
				case InfoKey: setForm.UpdateLayout( type ); break;
				case LogKey: logForm.UpdateLayout( type ); break;
				case TallyKey: tallyForm.UpdateLayout( type ); break;
			}
		}
	}
}

//
