/* 
 * 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 Plugin.Firebase.Firestore;

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

namespace iStatVball3;

/*
 * Data model used to persist custom dashboards. Persisted as an array of maps within the parent User document, NOT as
 * a root level collection.
 */
public class CustomDashboard : DXModel
{
	/* Properties */
	[FirestoreProperty("IsTeam1")] public bool IsTeam1 { get; set; }

	[FirestoreProperty("Name")] public string Name { get; set; }
	[FirestoreProperty("Description")] public string Description { get; set; }

	// Child reports (array)
	[FirestoreProperty("Reports")] public IList<CustomReport> Reports { get; set; }

	/* Ignored */
	[JsonIgnore] public JsonCategory JsonCategory { get; set; }

	/* Methods */
	public CustomDashboard()
	{}
		
	// Tests equality based on unique identifier
	public override bool Equals( object obj )
	{
		return (obj is CustomDashboard dashboard) && dashboard.UniqueId.Equals( UniqueId );
	}

	// Generates unique hash code, required for list de-duping
	public override int GetHashCode()
	{
		return UniqueId.GetHashCode();
	}

	// Returns canonical lookup key for this custom dashboard
	public string GetKey()
	{
		string name = DXUtils.ToCanonical( Name );

		// 'custom_foo'
		return $"{AnalyzeKeys.CustomKey}_{name}";
	}

	// Determines if specified dashboard name unique for current user
	public static bool IsUnique( string name, CustomDashboard dashboard )
	{
		IList<CustomDashboard> dashboards = Shell.CurrentUser.Dashboards;

		if ( dashboards != null )
		{
			foreach ( CustomDashboard test in dashboards )
			{
				// Do NOT include dashboard being edited
				if ( (test.Name == name) && !test.Equals( dashboard ) )
				{
					return false;
				}
			}
		}

		return true;
	}

	/* Permissions */

	// Determines if specified user can create custom dashboards		
	public static bool CanCreate( User user, Organization org )
	{
		// NA for sample org
		if ( !org.IsSample )
		{
			// Only Coach/Director/Stat have custom
			return user.Level switch
			{
				User.LevelType.Coach or 
				User.LevelType.Director or 
				User.LevelType.Statistician => true,
				
				_ => false
			};
		}

		// No one else does
		return user.IsAdmin;
	}

	// Determines if specified user can edit custom dashboards		
	public static bool CanEdit( User user )
	{
		// Only Coach/Director/Stat can edit
		return user.Level switch
		{
			User.LevelType.Coach or
			User.LevelType.Director or
			User.LevelType.Statistician => true,

			_ => false
		};
	}

	/* CRUD */

	// Performs cascading delete on this custom dashboard
	public async Task Delete()
	{
		// Child reports automatically deleted
		await Shell.CurrentUser.DeleteDashboard( this );

		// Clear from cache
		DashboardCache.Instance.RemoveCustom( this );
	}
}

//
