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

using System.Globalization;
using System.Text.RegularExpressions;

using DXLib.Utils;

namespace DXLib.Email;

/*
 * Provides utility methods for email address validation.
 */
public static class DXEmailUtils
{
	/* Methods */

	// Determines if value is valid list of comma-delimited email addresses
	public static bool IsValidList( string emailList )
	{
		string trimmed = DXUtils.RemoveSpaces( emailList );

		// Comma-delimited
		string[] emails = trimmed.Split( ",", StringSplitOptions.RemoveEmptyEntries );

		// Check all emails
		return emails.All( IsValid );
	}

	// Determines whether specified email address is valid format
	public static bool IsValid( string email )
	{
		// Must have value
		if ( string.IsNullOrEmpty( email ) )
		{
			return false;
		}

		// Validate domain name
		try
		{
			email = Regex.Replace( email, @"(@)(.+)$", DomainMapper, RegexOptions.None, TimeSpan.FromMilliseconds( 200 ) );
		}
		catch ( RegexMatchTimeoutException )
		{
			return false;
		}

		// Validate format
		try
		{
			return Regex.IsMatch( email,
								  @"^(?("")("".+?(?<!\\)""@)|(([0-9a-z]((\.(?!\.))|[-!#\$%&'\*\+/=\?\^`\{\}\|~\w])*)(?<=[0-9a-z])@))" +
								  @"(?(\[)(\[(\d{1,3}\.){3}\d{1,3}\])|(([0-9a-z][-0-9a-z]*[0-9a-z]*\.)+[a-z0-9][\-a-z0-9]{0,22}[a-z0-9]))$",
								  RegexOptions.IgnoreCase, TimeSpan.FromMilliseconds( 250 ) );
		}
		catch ( RegexMatchTimeoutException )
		{
			return false;
		}
	}

	// Used by IsValid to validate domain names
	private static string DomainMapper( Match match )
	{
		IdnMapping idn = new();

		string domainName = match.Groups[2].Value;

		try
		{
			domainName = idn.GetAscii( domainName );
		}
		catch ( ArgumentException )
		{
			return null;
		}

		return match.Groups[1].Value + domainName;
	}
}

//
