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

using System.Text.RegularExpressions;

using DXLib.UI.Form.Control;
using DXLib.Utils;

namespace DXLib.Video;

/*
 * A form control used to input a video File ID (YouTube or Vimeo). Basic validity checking is provided.
 */
public partial class DXVideoField : DXTextField
{
	/* Properties */
	
	// YouTube or Vimeo?
	public string Host { get => host; set => UpdateHost( value ); }
	
	/* Fields */
	private string host;
	
	/* Methods */
	public DXVideoField()
	{
		// Constant for video fields
		Title = "video.fileid";
		Help = "video.fileid";
		Hint = HintType.Custom;
		
		// Set defaults
		HasClear = true;
		MinLength = 0;
	}

	// Updates field based on YouTube/Vimeo host
	private void UpdateHost( string value )
	{
		host = value;

		UpdateState( false );
	}
	
	// Configures keyboard for Video ID input
	protected override void SetTextType( TextType type )
	{
		textField.Keyboard = Keyboard.Create( KeyboardFlags.None );
	}

	// Configures Video ID error hint text
	protected override void SetHintType( HintType type )
	{
		base.SetHintType( type );
		
		hintLbl.Text = DXString.Get( "form.hint.video" );
	}

	// Determines if specified value is valid YouTube video ID
	private static bool IsValidYouTube( string videoId )
	{
		Regex regex = YouTubeRegex();

		// Run regex
		bool valid = !string.IsNullOrEmpty( videoId ) && regex.IsMatch( videoId );

		return valid;
	}

	// Determines if specified value is valid Vimeo video ID
	private static bool IsValidVimeo( string videoId )
	{
		Regex regex = VimeoRegex();

		// Run regex
		bool valid = !string.IsNullOrEmpty( videoId ) && regex.IsMatch( videoId );

		return valid;
	}
	
	/* Abstracts */
	
	// Only valid if text is valid video ID
	public override bool IsValid()
	{
		// May be optional
		if ( !IsRequired )
		{
			return true;
		}

		// Host required
		if ( string.IsNullOrEmpty( Host ) )
		{
			return false;
		}

		string videoId = Text;

		// Validate host specific ID format 
		return Host switch
		{
			DXWebVideo.YouTubeHost => IsValidYouTube( videoId ),
			DXWebVideo.VimeoHost => IsValidVimeo( videoId ),
			
			_ => false
		};
	}

	/* Regex */
	
	// Validates YouTube video ID
    [GeneratedRegex("^[a-zA-Z0-9_-]{11}$")]
    private static partial Regex YouTubeRegex();
    
    // Validates Vimeo video ID
    [GeneratedRegex("^[0-9]+$")]
    private static partial Regex VimeoRegex();
}

//
