using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using iTextSharp.text.factories;
using Microsoft.Win32;
using System.Text.RegularExpressions;
using System.IO;
using iTextSharp.text;
namespace Volian.Base.Library
{
	/// 
	/// B2019-116 Volian.Base.Library This is a generic class for dealing with iTextSharp Fonts
	/// Code moved and consolidated from Volian.Print.Library Volian PDF.Library and VG
	/// 
	public static class VlnItextFont
	{
		private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
		private static string _PromsFontDir = null;//B2019-099 Consistent Font Retrieve
		/// 
		/// Register fonts based upon PromsFonts command line parameter
		/// 
		public static void RegisterPromsFonts()
		{
			_PromsFontDir = Volian.Base.Library.VlnSettings.GetCommand("PromsFonts", "");
			if (_PromsFontDir != "")
			{
				DirectoryInfo di = new DirectoryInfo(_PromsFontDir);
				if (di.Exists)
				{
					_MyLog.WarnFormat("PROMS Font Folder = {0}", _PromsFontDir); // C2019-028 Add info in the error log
					iTextSharp.text.FontFactory.RegisterDirectory(_PromsFontDir);
				}
			}
		}
		// B2019-174 created RegisterFontFolder so that we call at start of print() in PromsPrinter.cs
		//           this allows symbol characters to appear on the Auto Table Of Contents page
		public static void RegisterFontFolder()
		{
			if (_PromsFontDir == null || _PromsFontDir =="")//B2019-099 Consistent Font Retrieve
			{
				_PromsFontDir = Volian.Base.Library.VlnSettings.GetCommand("PromsFonts", "");
				if (_PromsFontDir == "")
					_PromsFontDir = FontFind.FontDir;
				else
				{
					DirectoryInfo di = new DirectoryInfo(_PromsFontDir);
					if (!di.Exists)
						_PromsFontDir = FontFind.FontDir;
					else
						_MyLog.WarnFormat("PROMS Font Folder = {0}", _PromsFontDir); // C2019-028 Add info in the error log
				}
			}
			int profileDepth1 = ProfileTimer.Push(">>>> RegisterDirectory " + _PromsFontDir);
			//_MyLog.DebugFormat("Register this Font Folder = {0}", _PromsFontDir); // debug
			iTextSharp.text.FontFactory.RegisterDirectory(_PromsFontDir);
			ProfileTimer.Pop(profileDepth1);
		}
		public static void RegisterFontByFontFolders(string fontName)
		{
			int profileDepth = ProfileTimer.Push(string.Format(">>>> RegisterFont {0}", fontName));
			if (!iTextSharp.text.FontFactory.IsRegistered(fontName))
			{
				RegisterFontFolder();
				if (!iTextSharp.text.FontFactory.IsRegistered(fontName))
				{
					//B2019-099 Consistent Font Retrieve
					_MyLog.WarnFormat("Problem with Font {0} in {1}", fontName, _PromsFontDir);
					if (_PromsFontDir != FontFind.FontDir)
					{
						int profileDepth2 = ProfileTimer.Push(">>>> RegisterDirectory " + FontFind.FontDir);
						//_MyLog.DebugFormat("Register this Font Folder = {0}", FontFind.FontDir); // debug
						iTextSharp.text.FontFactory.RegisterDirectory(FontFind.FontDir);
						ProfileTimer.Pop(profileDepth2);
						if (!iTextSharp.text.FontFactory.IsRegistered(fontName))
						{
							_MyLog.WarnFormat("Problem with Font {0} in {1}", fontName, FontFind.FontDir);
							int profileDepth3 = ProfileTimer.Push(">>>> RegisterDirectories");
							iTextSharp.text.FontFactory.RegisterDirectories();
							ProfileTimer.Pop(profileDepth3);
						}
						//else
						//{
						//	_MyLog.DebugFormat("Registered Font {0} in {1}", fontName, FontFind.FontDir); // debug
						//}
					}
					else
					{
						int profileDepth4 = ProfileTimer.Push(">>>> RegisterDirectories");
						//_MyLog.DebugFormat("RegistererDirectories {0}", FontFind.FontDir); // debug
						iTextSharp.text.FontFactory.RegisterDirectories();
						ProfileTimer.Pop(profileDepth4);
					}
				}
				if (!iTextSharp.text.FontFactory.IsRegistered(fontName))
				{
					_MyLog.WarnFormat("Font {0} could not be found!", fontName);
				}
				else
				{
					iTextSharp.text.Font fnt = iTextSharp.text.FontFactory.GetFont(fontName, 10);
					if (fnt.BaseFont == null)
					{
						_MyLog.WarnFormat("Font {0} is not installed properly!", fontName);
					}
				}
			}
			ProfileTimer.Pop(profileDepth);
		}
		private static RegistryKey _FontKey = Registry.LocalMachine.OpenSubKey("Software").OpenSubKey("Microsoft").OpenSubKey("Windows NT").OpenSubKey("CurrentVersion").OpenSubKey("Fonts");
		public static RegistryKey FontKey
		{ get { return _FontKey; } }
		/// 
		/// Try to register a particular font, if it fails register the entire font folder
		/// 
		/// FontName - Used to find a font file.
		public static void RegisterFont(string fontName)
		{
			if (!FontFactory.IsRegistered(fontName))
			{
				foreach (string name in FontKey.GetValueNames())
				{
					if (name.StartsWith(fontName))
					{
						string fontFile = (string)FontKey.GetValue(name);
						try // B2019-118 Add error handling for FontFacory.Register (Windows Registry contains a node that
								// points to a file that no longer exists
						{
							FontFactory.Register(fontFile.Contains("\\") ? fontFile : FontFind.FontDir + "\\" + fontFile);
						}
						catch (Exception ex) // catch any exception and add the error to the error log.
						{
							_MyLog.WarnFormat("Font Error {0} - {1}", name, ex.Message);
						}
					}
				}
				if (!FontFactory.IsRegistered(fontName))
					RegisterFontByFontFolders(fontName);
			}
		}
	}
	public static class FontFind
	{
		private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
		private static string _FontDir = null;
		public static string FontDir
		{
			get
			{
				if (_FontDir == null)
				{
					// B2019-112 Error Log Font Dir
					// C2019-028, B2019-099 Add call to .Net 4.6.1 method to get the system's windows font folder
					_FontDir = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Fonts);
					if (_FontDir != null) _MyLog.WarnFormat("Special Font Folder = {0}", _FontDir); // C2019-028 Add info in the error log
					if (_FontDir == null)
					{
						RegistryKey regKey = Registry.CurrentUser.OpenSubKey(@"Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders");
						if (regKey != null)
						{
							object obj = regKey.GetValue("Fonts");
							// B2019-099 Add more debug
							if (obj != null) _MyLog.WarnFormat("Font regkey.fonts = {0}", obj); // C2019-028 Add info in the error log
							// C2019-028 Add Null check before attempt to convert to string
							if (obj != null)
								_FontDir = obj.ToString();
						}
						if (_FontDir == null) // Not allowed or cannot find the fonts folder value in the registry.
						{
							_FontDir = @"C:\Windows\Fonts"; // default to C:\Windows\Fonts
							_MyLog.WarnFormat("FontDir set to default = {0}", _FontDir); // C2019-028 Add info in the error log
						}
					}
				}
				return _FontDir;
			}
		}
	}
}