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

using System.Globalization;

using RestSharp;
using CsvHelper;

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

using DXLib.Log;
using DXLib.Utils;

namespace iStatVball3;

/*
 * Entry point for all functionality for exporting stats to MaxPreps via REST API as well as for parsing school list CSV.
 */
public static class MP2Exporter
{
    /* Constants */

    // School list CSV
    private const string Filename = "maxpreps.csv";

    /* Methods */

    // Validates export then serializes and uploads stats for specified match
    public static async Task Export( Match match, Action callback )
    {
        Organization org = match.Season.Organization;

        // Organization must be High School
        if ( !org.IsHighSchool )
        {
            DXAlert.ShowOk( "maxpreps2.export", "maxpreps2.err.high", callback );
            return;
        }

        // Organization must be linked to MaxPreps
        if ( !org.HasMaxPreps )
        {
            DXAlert.ShowOk( "maxpreps2.export", "maxpreps2.err.org", callback );
            return;
        }

        // Match must have opponent
        if ( match.Opponent == null )
        {
            DXAlert.ShowOk( "maxpreps2.export", "maxpreps2.err.opponent", callback );
            return;
        }

        // Match opponent must be linked to MaxPreps
        if ( !match.Opponent.HasMaxPreps )
        {
            DXAlert.ShowOk( "maxpreps2.export", "maxpreps2.err.link", callback );
            return;
        }

        // Match has already been exported
        if ( match.Exported )
        {
            DXAlert.ShowOk( "maxpreps2.export", "maxpreps2.err.export", callback );
            return;
        }

        DXSpinner.Start();

        // OK to proceed
        await SendStats( match, callback );

        DXSpinner.Stop();

        // Done (success or fail)
        callback.Invoke();
    }

    // Serializes and uploads all stats for specified match
    private static async Task SendStats( Match match, Action callback )
    {
        try
        {
            MP2Match mp2Match = new();

            // Prep match for serialization
            await mp2Match.Populate( match );

            // Serialize/upload
            RestResponse response = await MP2API.SendStats( mp2Match );

            // Extract success/error
            MP2Response mp2Response = MP2Response.Deserialize( response );

            switch ( mp2Response.Status )
            {
                // Success
                case MP2Response.Success:
                {
                    await match.UpdateExported();

                    DXAlert.ShowOk( "maxpreps2.export", "maxpreps2.success", callback );
                    break;
                }
                // MaxPreps server error
                default:
                {
                    DXLog.Error( "maxpreps.sendstats", "response:{0}", response.Content );

                    DXAlert.ShowOk( "maxpreps2.export", "maxpreps2.err", mp2Response.Errors[0], callback );
                    break;
                }
            }
        }
        // Unknown error
        catch ( Exception ex )
        {
            DXLog.Exception( "maxpreps.sendstats", ex );

            DXAlert.ShowOk( "maxpreps2.export", "maxpreps2.err.send", callback );
        }
    }

    // Reads full list of schools (~29K) from local CSV file
    public static async Task<List<MP2School>> ReadSchools()
    {
        Stream stream = await DXResource.OpenFile( Filename );
        
        // Open CSV file
        using StreamReader reader = new( stream );
        using CsvReader csv = new( reader, CultureInfo.InvariantCulture );

        await csv.ReadAsync();
        csv.ReadHeader();

        List<MP2School> schoolList = new();

        // Parse each comma-delimited row
        while ( await csv.ReadAsync() )
        {
            MP2School school = new()
            {
                SchoolId = csv.GetField( "SchoolId" )?.Trim(),
                FormattedName = csv.GetField( "FormattedName" )?.Trim(),
                Name = csv.GetField( "Name" )?.Trim(),
                Mascot = csv.GetField( "Mascot" )?.Trim(),
                Address = csv.GetField( "Address" )?.Trim(),
                Address2 = csv.GetField( "Address2" )?.Trim(),
                City = csv.GetField( "City" )?.Trim(),
                State = csv.GetField( "State" )?.Trim(),
                Zip = csv.GetField( "Zip" )?.Trim()
            };

            schoolList.Add( school );
        }

        return schoolList;
    }
}

//
