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

using Plugin.Firebase.Firestore;

using FFImageLoading;
using FFImageLoading.Cache;

namespace DXLib.Data.Model;

/*
 * Extends the base model to add functionality for reading and writing a model image (avatar) from remote Firebase Cloud
 * Storage.
 */
public abstract class DXImageModel : DXModel
{
	/* Constants */
	public const string ContentType = "image/jpeg";
	public const string FileExt = "jpg";

	// URI escaping
	private const string Slash = "/";
	private const string EscapedSlash = "%2F";

	// Required for Firestore Storage image URIs
	private const string StoragePath = "https://firebasestorage.googleapis.com/v0/b/istatvball-3x.appspot.com/o/";
	private const string StorageParams = "?alt=media";

    /* Properties */
    [FirestoreProperty("ImageUrl")] public string ImageUrl { get; set; }

	/* Methods */
	protected DXImageModel()
	{}

	/* CRUD */

	// Deletes document (and image) for this object
	public override async Task Delete( bool remove = true )
	{
		await DeleteImage();

		await base.Delete( remove );
	}

	// Deletes document image, if any
	private async Task DeleteImage()
	{
		if ( ImageUrl != null )
		{
			string url = DXData.CreateUrl( BaseCollectionKey, UniqueId, FileExt );

			await DXData.DeleteStorage( url );
		}
	}

	// Builds absolute URL used for reading remote image
	public static string GetAbsoluteUrl( string path )
	{
		// MUST escape '/'
		string escapedUrl = path.Replace( Slash, EscapedSlash );

		// MUST manually build URI for images (not using DXData)
		Uri uri = new( $"{StoragePath}{escapedUrl}{StorageParams}" );

		return uri.ToString();
	}

	// Builds relative URL to be saved in model
	public static string GetRelativeUrl( DXImageModel model )
	{
		string path = model.BaseCollectionKey.ToLower();
		string file = model.UniqueId;

		// 'players/abc-123.jpg' (must NOT escape '/')
		return $"{path}/{file}.{FileExt}";
	}

	// Clears image for this model from local image cache
    public async Task ClearCache()
    {
        if ( ImageUrl != null )
        {
            // Cache key is full URL
            string key = GetAbsoluteUrl( ImageUrl );

            // Clear memory/disk caches and all sample sizes
            await ImageService.Instance.InvalidateCacheEntryAsync( key, CacheType.All, true );
        }
    }
}

//
