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

using System.Text.Json.Serialization;

using DXLib.Data;
using DXLib.Data.Model;

namespace iStatVball3;

/*
 * Persists all stats for an individual set following completion of the set. Improves fetch performance for analysis by
 * persisting stats as a serialized file to Firebase Cloud Storage apart from Firestore. Performance is further improved
 * by also saving a copy to a local MonkeyBarrel cache.
 *
 * DXModel for base fields only, NOT Firestore persisted.
 */
public class SetData : DXModel
{
	/* Constants */
	private const string FilePath = "data/stats";
	private const string FileExt = "gz";

	/* Properties */

	// Children (array of maps)
	public IList<Stat> Stats { get; set; }

	// Parent (FK)
	public string SetId { get; set; }

	/* Ignored */

	// Current stat count
	[JsonIgnore] public int Count => Stats?.Count ?? -1;
	[JsonIgnore] public bool IsEmpty => (Count <= 0);

	/* Local Cache */

	// Reads and returns SetData object from local cache
	public static SetData ReadLocal( string key )
	{
		return DXData.ReadCache<SetData>( key );
	}

	// Caches entire SetData object locally
	public void WriteLocal( bool replace )
	{
		DXData.WriteCache( SetId, this, replace );
	}

	// Delete specified set stats data from local cache
	public static void DeleteLocal( Set set )
	{
		DXData.DeleteCache( set.UniqueId );
	}

	/* Cloud Cache */

	// Deserializes remote JSON and returns as SetData object
	public static async Task<SetData> ReadCloud( string setId, bool alert = true )
	{
		return await DXData.ReadStorage<SetData>( CreateUrl( setId ), alert );
	}

	// Writes entire SetData object as serialized, compressed JSON
	public async Task WriteCloud( bool replace, Action callback = null )
	{
		string url = CreateUrl( SetId );

		// Optionally delete existing file first
		if ( replace )
		{
			await DXData.DeleteStorage( url );
		}

		// Write new file
		await DXData.WriteStorage( url, this, callback );
	}

	// Deletes specified set stats data from cloud cache
	public static async Task DeleteCloud( Set set )
	{
		string url = CreateUrl( set.UniqueId );
		
		// Delete cloud cache
		await DXData.DeleteStorage( url );
	}

	// Builds remote Firebase Cloud Storage file URL
	private static string CreateUrl( string uniqueId )
	{
		return DXData.CreateUrl( FilePath, uniqueId, FileExt );
	}
}

//
