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

using Newtonsoft.Json;

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

using DXLib.Email;
using DXLib.Utils;

namespace iStatVball3;

/*
 * Main entry point for the original, file export style MaxPreps integration. Serializes match stats into MaxPreps format,
 * then attaches the file to an email for export.
 */
public static class MPExporter
{
	/* Constants */
	private const string FilePrefix = "istatvball3_maxpreps";
	private const string FileExt = "txt";
	private const string FileType = "text/plain";

	// SendGrid dynamic template
	private const string TemplateId = "d-1120cd19fba34a0abc6dc47751123633";

	/* Methods */

	// Serializes and emails stats for specified match
	public static async Task Export( Match match, Action callback )
	{
		DXSpinner.Start();

        string email = Shell.CurrentUser.Username;

        // Local (AppleMail)
        if ( Shell.Settings.IsLocalEmail )
        {
            await StartExport( match, email, true, callback );
        }
        // Cloud (SendGrid)
        else
        {
	        async void Action( string entered ) => await OnEmailEntered( match, entered, callback );

	        DXInputAlert.ShowEmail( "maxpreps.title", "maxpreps.msg", email, Action, callback );
        }
	}

	// User entered destination email address for Cloud send
	private static async Task OnEmailEntered( Match match, string email, Action callback )
	{
		bool local = Shell.Settings.IsLocalEmail;

		await StartExport( match, email, local, callback );
	}

	// Starts export flow
    private static async Task StartExport( Match match, string email, bool local, Action callback )
    {
        // Async send export email
        DXEmail.Result result = await SendStats( match, email, local );

        switch ( result )
        {
            // Success
            case DXEmail.Result.Success:
            {
                DXAlert.ShowOk( "maxpreps.title", "maxpreps.success", callback );
                break;
            }
            // Email not supported
            case DXEmail.Result.ErrorUnsupported:
            {
                DXAlert.ShowError( "maxpreps.err.support", callback );
                break;
            }
            // Error
            case DXEmail.Result.Error:
            {
                DXAlert.ShowError( "maxpreps.err", callback );
                break;
            }
            default: break;
        }
    }

	// Used internally to serialize match stats and send via email
    private static async Task<DXEmail.Result> SendStats( Match match, string email, bool local )
	{
        // Serialize MaxPreps data
        string data = await MPSerializer.Serialize( match );

		// Dynamic fields
		string team = match.Team1Name;
		string opponent = match.IsAnonOpponent ? "--" : match.Team2Name;
		string date = DXUtils.MonthTimeFromDate( match.MatchTime );

        // Async email send
        DXEmail.Result result = await DXEmail.Send( new DXEmailConfig
		{
            // Native app or cloud?
            IsLocal = local,

            // From:
	        FromAddress = DXString.Get( "email.address" ),
			FromName = DXString.Get( "email.name" ),

			// To:
			ToAddress = email,
			ToName = null,

            // Local use only
            Subject = DXString.Get( "maxpreps.subject" ),
			Body = DXString.Get( "maxpreps.body", team, opponent, date ),

            // Template
            TemplateId = TemplateId,
			TemplateData = new MaxPrepsEmail
			{
				Team = team,
				Opponent = opponent,
				Date = date
			},

			// Attachment
			FileRaw = DXUtils.ToBytes( data ),
			FileName = CreateFilename( match ),
			FileData = DXUtils.ToBase64( data ),
			FileType = FileType
		});

		DXSpinner.Stop();

		return result;
	}

	// Generates canonical filename for export file
	private static string CreateFilename( Match match )
	{
		// Use opponent name and match date in filename 'hawaii_190926'
		string date = DXUtils.FilenameFromDate( match.MatchTime );
		string name = match.IsAnonOpponent ? match.Name : $"{match.Name}_{date}";

		// Build canonical form 'istatvball_maxpreps_hawaii_190926.txt'
		string fullName = $"{FilePrefix}_{name}.{FileExt}";
		string filename = DXUtils.ToFilename( fullName );

		return filename;
	}
}

/*
 * Encapsulates properties for populating dynamic SendGrid email template.
 */
public class MaxPrepsEmail
{
	/* Properties */
	[JsonProperty( "team" )]
	public string Team { get; set; }

	[JsonProperty( "opponent" )]
	public string Opponent { get; set; }

	[JsonProperty( "date" )]
	public string Date { get; set; }
}

//
