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

using FFImageLoading.Maui;

using DXLib.Data.Model;

namespace DXLib.UI.Control.Image;

/*
 * A simple wrapper for an FFImageLoading.CachedImage. The image can be loaded from any of the following sources:
 *   . Byte array
 *   . Existing image source
 *   . Local resource file
 *   . Remote cloud storage URL
 */
public class DXImage : CachedImage
{
	/* Constants */
	public const int DefaultDuration = 90;
	public const int JpegQuality = 92;

	/* Properties */
	public LayoutOptions Horizontal { set => HorizontalOptions = value; }
	public LayoutOptions Vertical { set => VerticalOptions = value; }
	
	/* Methods */
	public DXImage()
	{
		Aspect = Aspect.AspectFit;

		// Cache config
		CacheType  = FFImageLoading.Cache.CacheType.All;
		CacheDuration = TimeSpan.FromDays( DefaultDuration );

		// Save memory/performance by down sampling
		Aspect = Aspect.AspectFit;
		DownsampleToViewSize = true;
		BitmapOptimizations = true;

		// Remote download config
		FadeAnimationEnabled = true;
		FadeAnimationDuration = 500;
		FadeAnimationForCachedImages = false;
		
		RetryCount = 3;
		RetryDelay = 500;
	}

	// Shorthand for setting image dimensions
	public void SetSize( double width, double height )
	{
		WidthRequest = width;
		HeightRequest = height;

		if ( DownsampleToViewSize )
		{
			DownsampleWidth = width;
			DownsampleHeight = height;
		}
	}
	
	/* Read */

	// Loads image from specified JPG byte array
	public void FromByteArray( byte[] bytes )
	{
		Source = ImageSource.FromStream( () => new MemoryStream( bytes ) );
	}

	// Loads image from existing in-memory image source
	public void FromSource( ImageSource source )
	{
		Source = source;
	}

	// Loads image from specified local resource file
	public void FromResource( string resource )
	{
		Source = resource;
	}

	// Loads image from remote cloud storage URL
	public void FromUrl( string url )
	{
		Source = DXImageModel.GetAbsoluteUrl( url );
	}

	/* Write */

	// Converts this image to JPG byte array at specified dimensions
	public async Task<byte[]> ToByteArray( int width, int height )
	{
		return await GetImageAsJpgAsync( JpegQuality, width, height );
	}
}

//
