﻿/*****************************************************************************
*       Copyright 1985, 2020 Precisely.
*       All rights reserved.
*
*       This document contains unpublished, confidential, and proprietary
*       information of Precisely. No disclosure or use of any portion of
*       the contents of this document may be made without the express 
*       written consent of Precisely.
*****************************************************************************/
using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Security.AccessControl;
using System.Text;
using System.Windows;
using System.Windows.Input;
using System.Windows.Interop;
using MapInfo.MiPro.Samples.LayoutTemplate.Properties;
using MapInfo.MiPro.Samples.LayoutTemplate.ViewModel;
using MapInfo.Types;
using Microsoft.Win32;
using static System.String;
using MessageBox = System.Windows.MessageBox;

namespace MapInfo.MiPro.Samples.LayoutTemplate.Command
{
	/// <summary>
	/// Save Layout as Template Command
	/// </summary>
	/// <seealso cref="System.Windows.Input.ICommand" />
	public class SaveLayoutAsTemplateCommand : ICommand
	{
		private readonly IMapInfoPro _application;
		private int _mapIndex;
		private int _browserIndex;
		private int _legendIndex;
		private string _templateFolderPath;
		private HashSet<string> _itemNamelist;
		public SaveLayoutAsTemplateCommand(IMapInfoPro application)
		{
			if (application == null)
				throw new ArgumentNullException(nameof(application));

			_application = application;
		}

		public bool CanExecute(object parameter)
		{
			var activeLayoutWindow = LayoutHelper.GetActiveLayoutwindow(_application);
			return activeLayoutWindow != null;
		}

		public event EventHandler CanExecuteChanged;

		protected virtual void OnCanExecuteChanged()
		{
			var handler = CanExecuteChanged;
			handler?.Invoke(this, EventArgs.Empty);
		}

		/// <summary>
		/// Called when the command is invoked.
		/// </summary>
		/// <param name="parameter">Data used by the command.  If the command does not require data to be passed, this object can be set to null.</param>
		public void Execute(object parameter)
		{
			try
			{
				SaveLayoutAsTemplate();
			}
			catch (Exception ex)
			{
				MessageBox.Show(string.Format(Resource.ErrorMessage_UnableToSaveTemplate, ex.Message), Resource.MB_IDS_ADDIN_NAME);
			}
		}
		/// <summary>
		/// Create a folder and save template and related data and create a zip file.
		/// </summary>
		/// <param name="dialogViewModel">SaveTemplateDialogViewModel</param>
		private void ExportAsZipFile(SaveTemplateDialogViewModel dialogViewModel)
		{
			if (string.IsNullOrEmpty(dialogViewModel.FileName))
			{
				return;
			}
			string folderName = null;
			try
			{
				SaveFileDialog saveFileDialog = new SaveFileDialog()
				{
					InitialDirectory = @"C:\",
					RestoreDirectory = true,
					Filter = Resource.TemplateZipFilter,
					FileName = dialogViewModel.FileName,
					Title = Resource.TemplateExportDialogTitle
				};
				
				var result = saveFileDialog.ShowDialog();
				if (result == true)
				{
					String file = saveFileDialog.FileName;
					if (!string.IsNullOrEmpty(file))
					{
						string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(file);
						folderName = Path.GetDirectoryName(file);
						if (String.IsNullOrEmpty(folderName))
						{
							return;
						}
						// create folder name having same name as of zip file
						folderName = Path.Combine(folderName, fileNameWithoutExtension);
						// check folder is already there or not
						if (!Directory.Exists(folderName))
						{
							// create temporary folder
							Directory.CreateDirectory(folderName);
						}
						else
						{
							MessageBox.Show(string.Format(Resource.ErrorMessage_DirectoryAlreadyExist, folderName),
								Resource.MB_IDS_ADDIN_NAME);
							return;
						}
						string layFileName = Path.Combine(folderName, dialogViewModel.FileNameWithExtension);
						string templateMetadataFolderPath = Path.Combine(folderName, dialogViewModel.FileName);
						CreateLayFile(layFileName, templateMetadataFolderPath);
						string thumbnailFolderPath = Path.Combine(folderName, dialogViewModel.FileName);
						var thumbnailPath = CreateThumbnail(thumbnailFolderPath, dialogViewModel.FileName);
						TemplateFile templateFile = new TemplateFile
						{
							ThumbnailPath = thumbnailPath,
							FileName =
								dialogViewModel.FileNameWithExtension,
							TemplateName = dialogViewModel.Name,
							TemplateDescription = dialogViewModel.Description,
							TemplateFolderPath = LayoutHelper.GetDirectoryName(dialogViewModel.TemplateFolderPath),
						};
						// save xml file
						if (LayoutTemplateFileManager.Instance.SaveTemplate(templateFile, folderName))
						{
							// check same name zip file exist and delete it if exist.
							if (File.Exists(saveFileDialog.FileName))
							{
								File.Delete(saveFileDialog.FileName);
							}
							// create zip file from the folder
							ZipFile.CreateFromDirectory(folderName, saveFileDialog.FileName);
						}
						// delete temporary folder
						Directory.Delete(folderName, true);
					}
				}
			}
			catch (Exception ex)
			{
				if (!String.IsNullOrEmpty(folderName) && Directory.Exists(folderName))
				{
					Directory.Delete(folderName,true);
				}
				MessageBox.Show(ex.ToString(), Resource.MB_IDS_ADDIN_NAME);
			}
		}
		/// <summary>
		/// Create thumbnail
		/// </summary>
		/// <param name="templateFolderPath">template metadata folder path</param>
		/// <param name="fileName">file name of thumbnail</param>
		/// <returns>return the path of thumbnail if success else null;</returns>
		private string CreateThumbnail(string templateFolderPath, string fileName)
		{
			if (String.IsNullOrEmpty(templateFolderPath)
			    || string.IsNullOrEmpty(fileName))
			{
				return null;
			}
			if (!Directory.Exists(templateFolderPath))
			{
				Directory.CreateDirectory(templateFolderPath);
			}
			IWindowInfo winInfo = LayoutHelper.GetActiveLayoutwindow(_application);
			var layoutWindowId = winInfo.WindowId;

			int currentPage = LayoutHelper.GetLayoutCurrentPage(_application, layoutWindowId);
			//Set to first page to get its thumbnail
			LayoutHelper.SetCurrentPage(_application, layoutWindowId, 1);
			var thumbnailPath = LayoutTemplateFileManager.Instance.GenerateThumbnail(templateFolderPath,
				fileName, layoutWindowId, _application);
			//Set back to current page
			LayoutHelper.SetCurrentPage(_application, layoutWindowId, currentPage);
			return thumbnailPath;
		}
		/// <summary>
		/// create lay file
		/// </summary>
		/// <param name="layFileFullPath">lay file full path</param>
		/// <param name="templateFolderPath">template metadata folder path</param>
		private void CreateLayFile(string layFileFullPath, string templateFolderPath)
		{
			if (!Directory.Exists(templateFolderPath))
			{
				Directory.CreateDirectory(templateFolderPath);
			}
			_templateFolderPath = templateFolderPath;
			IWindowInfo winInfo = LayoutHelper.GetActiveLayoutwindow(_application);
			var layoutWindowId = winInfo.WindowId;

			var mapBasic = $"Set {_application.EvalMapBasicCommand("SessionInfo(1)")}";
			_application.RunMapBasicCommand($"Set CoordSys Layout { GetUnitsText()}", false);

			var numberOfPages = Convert.ToInt32(_application.EvalMapBasicCommand($"LayoutInfo({layoutWindowId},11)"));
			var isMultiPage = numberOfPages > 1;
			var templateFile = new StringBuilder();
			AppendTemplateHeader(templateFile);
			AppendLayoutHeader(templateFile, layoutWindowId);
			_itemNamelist = LayoutHelper.GetItemNameList(_application, layoutWindowId);
			ResetItemsIndex();
			for (int pageCount = 1; pageCount <= numberOfPages; pageCount++)
			{
				if (pageCount > 1)
					templateFile.AppendLine(2, "Add Designer Page Window FrontWindow()");

				if (isMultiPage)
					templateFile.AppendLine(2, $"Set Layout Window FrontWindow() Page {pageCount}");

				var numItems = Convert.ToInt32(_application.EvalMapBasicCommand($"LayoutPageItemInfo({layoutWindowId}, {pageCount}, -1, 22)"));
				for (int layoutItemId = 1; layoutItemId <= numItems; layoutItemId++)
				{
					AppendLayoutItem(templateFile, layoutItemId, layoutWindowId, pageCount);
				}
			}

			if (isMultiPage)
				templateFile.AppendLine(2, "Set Layout Window FrontWindow() Page 1");

			AppendLayoutFooter(templateFile, layoutWindowId);
			AppendTemplateFooter(templateFile);
			_application.RunMapBasicCommand(mapBasic, false);

			using (FileStream fs = new FileStream(layFileFullPath, FileMode.Create))
			{
				// Always encode with UTF-8 to support localized text in any language.
				using (StreamWriter writer = new StreamWriter(fs, Encoding.UTF8))
				{
					writer.Write(templateFile.ToString());
				}
			}
		}
		/// <summary>
		/// Save the template
		/// </summary>
		private void SaveLayoutAsTemplate()
		{
			var validationPassed = false;
			_templateFolderPath = null;
			bool isOverwrite = false;
			SaveTemplateDialogViewModel dialogViewModel = null;
			String oldName = "";
			String oldDescription = "";
			String selectedOption = null;
			do
			{
				if (dialogViewModel != null)
				{
					oldName = dialogViewModel.Name;
					oldDescription = dialogViewModel.Description;
					selectedOption = dialogViewModel.SelectedSaveOption;
				}
				dialogViewModel = new SaveTemplateDialogViewModel(_application, true)
				{
					Name = oldName,
					Description = oldDescription,
					SelectedSaveOption = selectedOption
				};
				var saveTemplateDialog =
					new View.SaveTemplateDialog(_application, Resource.SaveTemplate_Title, ref dialogViewModel);
				// ReSharper disable once UnusedVariable
				var helper = new WindowInteropHelper(saveTemplateDialog) { Owner = _application.MainHwnd };
				saveTemplateDialog.ShowDialog();

				if (IsNullOrEmpty(dialogViewModel.FileName) || !dialogViewModel.IsOk)
				{
					return;
				}
				// if export as zip is selected 
				if (dialogViewModel.SelectedSaveOption == Resource.Template_SaveOption_ExportAsZipFile)
				{
					ExportAsZipFile(dialogViewModel);
					return;
				}
				//check for directory permission
					if (!LayoutHelper.DirectoryHasPermission(dialogViewModel.SelectedSaveOptionType(), FileSystemRights.Write | FileSystemRights.CreateDirectories))
				{
					MessageBox.Show(
						String.Format(Resource.TemplateGalleryShared_DeleteAccess_Error, LayoutTemplateFileManager.Instance.TemplateTypeToFolderPath(dialogViewModel.SelectedSaveOptionType())),
						Resource.MB_IDS_ADDIN_NAME);
					return;
				}

				LayoutTemplateFiles templateFiles = LayoutTemplateFileManager.Instance.TemplateTypeToTemplateFiles(dialogViewModel.SelectedSaveOptionType());
				if (templateFiles == null)
				{
					return;
				}
				if (templateFiles.Any(
					item => string.Compare(item.TemplateName, dialogViewModel.Name, StringComparison.OrdinalIgnoreCase) == 0))
				{
					if (MessageBox.Show(Format(Resource.SaveTemplate_TemplateAlreadyExistMessage, dialogViewModel.Name),
							Resource.SaveTemplate_Title,
							MessageBoxButton.YesNo) == MessageBoxResult.Yes)
					{
						
						var existingTemplate = templateFiles.FirstOrDefault(
							item => String.Compare(item.TemplateName, dialogViewModel.Name, StringComparison.OrdinalIgnoreCase)==0);
						if (!LayoutTemplateFileManager.Instance.RemoveTemplateFile(existingTemplate, templateFiles))
						{
							return;
						}
						isOverwrite = true;
						validationPassed = true;
					}
				}
				else
				{
					validationPassed = true;
				}
			} while (!validationPassed);

			if (File.Exists(dialogViewModel.FullFilePath) && !isOverwrite)
			{
				dialogViewModel.FileName = LayoutHelper.GetUniqueFileName(dialogViewModel.FileName);
			}
			CreateLayFile(dialogViewModel.FullFilePath, dialogViewModel.TemplateFolderPath);
			var thumbnailPath = CreateThumbnail(dialogViewModel.TemplateFolderPath, dialogViewModel.FileName);

			LayoutTemplateFileManager.Instance.AddTemplateFile(new TemplateFile
			{
				ThumbnailPath = thumbnailPath,
				FileName =
					dialogViewModel.FileNameWithExtension,
				TemplateName = dialogViewModel.Name,
				TemplateDescription = dialogViewModel.Description,
				TemplateFolderPath= LayoutHelper.GetDirectoryName(dialogViewModel.TemplateFolderPath),
				Type = dialogViewModel.SelectedSaveOptionType()
			});
		}

		#region private methods

		/// <summary>
		/// Resets the index of the items like maps, browsers.
		/// </summary>
		private void ResetItemsIndex()
		{
			_mapIndex = 1;
			_browserIndex = 1;
			_legendIndex = 1;
		}

		/// <summary>
		/// Appends the template header.
		/// Always set Charset to UTF-8 to support localized text in any language.
		/// </summary>
		/// <param name="templateFile">The template file.</param>
		private void AppendTemplateHeader(StringBuilder templateFile)
		{
			templateFile.AppendLine("!Workspace");
			templateFile.AppendLine($"!Version {Resource.Template_ApplicationVersion}");
			templateFile.AppendLine("!Charset UTF-8");
		}

		/// <summary>
		/// Appends the layout header.
		/// </summary>
		/// <param name="templateFile">The template file.</param>
		/// <param name="layoutWindowId">The layout window identifier.</param>
		private void AppendLayoutHeader(StringBuilder templateFile, int layoutWindowId)
		{
			templateFile.AppendLine("Layout Designer");
			templateFile.AppendLine(2,
				$"Width {_application.EvalMapBasicCommand($"LayoutInfo({layoutWindowId}, 2)")} {GetUnitsText()}");
			templateFile.AppendLine(2,
				$"Height {_application.EvalMapBasicCommand($"LayoutInfo({layoutWindowId}, 3)")} {GetUnitsText()}");
			templateFile.AppendLine(2, "Dim uniqueLayoutWin As Integer");
			templateFile.AppendLine(2, "uniqueLayoutWin = FrontWindow()");
			templateFile.AppendLine(2, "Dim restoreCoordSysString As String");
			templateFile.AppendLine(2, "restoreCoordSysString = \"Set \" + SessionInfo(1)");
			templateFile.AppendLine(2, $"Set CoordSys Layout {GetUnitsText()}");
			templateFile.AppendLine(2,
				$"Set Layout Window uniqueLayoutWin Zoom {_application.EvalMapBasicCommand($"LayoutInfo({layoutWindowId}, 8)")} Center({ _application.EvalMapBasicCommand($"LayoutInfo({layoutWindowId}, 9)")} , {_application.EvalMapBasicCommand($"LayoutInfo({layoutWindowId}, 10)") })");
		}

		/// <summary>
		/// Appends the layout footer.
		/// </summary>
		/// <param name="templateFile">The template file.</param>
		/// <param name="windowId">The window identifier.</param>
		private void AppendLayoutFooter(StringBuilder templateFile, int windowId)
		{
			AppendPageInformation(templateFile, windowId);
		}

		/// <summary>
		/// Appends the template footer.
		/// </summary>
		/// <param name="templateFile">The template file.</param>
		private void AppendTemplateFooter(StringBuilder templateFile)
		{
			templateFile.AppendLine("Run Command restoreCoordSysString");
			templateFile.AppendLine("Undim restoreCoordSysString");
			templateFile.AppendLine("UnDim uniqueLayoutWin");
		}

		/// <summary>
		/// Appends the page inforation.
		/// </summary>
		/// <param name="templateFile">The template file.</param>
		/// <param name="windowId">The window identifier.</param>
		private void AppendPageInformation(StringBuilder templateFile, int windowId)
		{
			string pageOrientation = "Portrait";
			var orientation = LayoutHelper.GetWindowInfo(_application, windowId, 22);
			if (!String.IsNullOrEmpty(orientation))
			{
				var pageOrientationNumber = Convert.ToInt32(orientation);
				if (pageOrientationNumber == 1)
					pageOrientation = "Portrait";
				else if (pageOrientationNumber == 2)
					pageOrientation = "Landscape";
			}

			var paperSize = LayoutHelper.GetWindowInfo(_application, windowId, 24);
			var printerName = LayoutHelper.GetWindowInfo(_application, windowId, 21);
			var numCopies = LayoutHelper.GetWindowInfo(_application, windowId, 23);
			var leftMargin = LayoutHelper.GetWindowInfo(_application, windowId, 25);
			var rightMargin = LayoutHelper.GetWindowInfo(_application, windowId, 26);
			var topMargin = LayoutHelper.GetWindowInfo(_application, windowId, 27);
			var bottomMargin = LayoutHelper.GetWindowInfo(_application, windowId, 28);
			var resolution = LayoutHelper.GetWindowInfo(_application, windowId, 52);

			string mb = "Set Window FrontWindow() Printer";

			if (!String.IsNullOrEmpty(printerName))
			{
				mb += $" Name \"{printerName}\"";
			}
			if (!String.IsNullOrEmpty(pageOrientation))
			{
				mb += $" Orientation {pageOrientation}";
			}
			if (!String.IsNullOrEmpty(numCopies))
			{
				mb += $" Copies {numCopies}";
			}
			if (!String.IsNullOrEmpty(paperSize))
			{
				mb += $" Papersize {paperSize}";
			}
			if (!String.IsNullOrEmpty(resolution))
			{
				mb += $" Resolution {resolution}";
			}
			if (!IsMarginsZero(leftMargin,rightMargin,topMargin,bottomMargin))
			{
				mb += $" Margins Left {leftMargin} Right {rightMargin} Top {topMargin} Bottom {bottomMargin} {GetUnitsText()}";
			}
			templateFile.AppendLine(mb);
		}
		/// <summary>
		/// Return true if all margins are 0 else false
		/// </summary>
		/// <param name="leftMargin">Left Margin</param>
		/// <param name="rightMargin">Right Margin</param>
		/// <param name="topMargin">Top Margin</param>
		/// <param name="bottomMargin">Bottom Margin</param>
		/// <returns>Return true if all margins are 0 else false</returns>
		private bool IsMarginsZero(string leftMargin, string rightMargin, string topMargin, string bottomMargin)
		{
			if ((!String.IsNullOrEmpty(leftMargin) && leftMargin == "0")
			    || (!String.IsNullOrEmpty(rightMargin) && rightMargin == "0")
			    || (!String.IsNullOrEmpty(topMargin) && topMargin == "0")
			    || (!String.IsNullOrEmpty(bottomMargin) && bottomMargin == "0"))
			{
				return true;
			}
			else
			{
				return false;
			}
		}

		/// <summary>
		/// Appends the layout item.
		/// </summary>
		/// <param name="templateFile">The template file.</param>
		/// <param name="itemId">The item identifier.</param>
		/// <param name="layoutWindowId">The layout window identifier.</param>
		/// <param name="pageIndex">Index of the page.</param>
		private void AppendLayoutItem(StringBuilder templateFile, int itemId, int layoutWindowId, int pageIndex)
		{
			var itemInfo = _application.EvalMapBasicCommand($"LayoutPageItemInfo({layoutWindowId},{pageIndex},{itemId},11)");
			switch (Convert.ToInt32(itemInfo))
			{
				case 0: // empty frame
					AppendLayoutItemEmpty(templateFile, layoutWindowId, itemId, pageIndex);
					break;

				case 1: // map
					AppendLayoutItemMapper(templateFile, layoutWindowId, itemId, pageIndex);
					break;

				case 2: // browser
					AppendLayoutItemBrowser(templateFile, layoutWindowId, itemId, pageIndex);
					break;

				case 3: // legend
					AppendLayoutItemLegends(templateFile, layoutWindowId, itemId, pageIndex);
					break;

				case 4: // text
					AppendLayoutItemText(templateFile, layoutWindowId, itemId, pageIndex);

					break;

				case 5: // shape
					AppendLayoutItemShape(templateFile, layoutWindowId, itemId, pageIndex);
					break;

				case 6: // image
					AppendLayoutItemImage(templateFile, layoutWindowId, itemId, pageIndex);
					break;

				case 7: // custom 
					AppendLayoutItemCustomFrame(templateFile, layoutWindowId, itemId, pageIndex);
					break;
			}
		}
		/// <summary>
		/// Get the file name having the given extension in given folder 
		/// </summary>
		/// <param name="folder">Folder path</param>
		/// <param name="extension">extension</param>
		/// <returns>file name</returns>
		private string GetfileName(string folder, string extension)
		{
			string[] files = Directory.GetFiles(folder);
			foreach (var file in files)
			{
				var fileExtension = Path.GetExtension(file);
				if (fileExtension != null && fileExtension.ToLower() == extension)
				{
					return Path.GetFileName(file);
				}
			}
			return "";
		}
		/// <summary>
		/// copy image to images folder under template folder
		/// </summary>
		/// <param name="imageFilePath">source image file path</param>
		/// <returns>destination file path where image is copied</returns>
		private string CopyImagetoImagesFolder(string imageFilePath)
		{
			try
			{
				string imagesFolderPath = Path.Combine(_templateFolderPath, Constant.ImagesFolderName);
				if (!Directory.Exists(imagesFolderPath))
				{
					Directory.CreateDirectory(imagesFolderPath);
				}
				string fileName = Path.GetFileName(imageFilePath);
				if (fileName != null)
				{
					string destFilePath = Path.Combine(Path.Combine(_templateFolderPath, Constant.ImagesFolderName), fileName);
					File.Copy(imageFilePath, destFilePath, true);
					return destFilePath;
				}

				return null;
			}
			catch
			{
				return null;
			}

		}

		private string GetCustomFrameFolderName()
		{
			bool found;
			string directoryName;
			int id = 1;
			do
			{
				directoryName = _templateFolderPath;
				directoryName += string.Format("\\CustomFrame_{0}", id++);
				found = Directory.Exists(directoryName);
			} while (found);
			return directoryName;
		}
		/// <summary>
		/// Appends the layout item custom control
		/// </summary>
		/// <param name="templateFile">template file</param>
		/// <param name="layoutWindowId">layout window id</param>
		/// <param name="itemId">ItemId</param>
		/// <param name="pageIndex">Index of the page.</param>
		private void AppendLayoutItemCustomFrame(StringBuilder templateFile, int layoutWindowId, int itemId, int pageIndex)
		{
			string dir = GetCustomFrameFolderName();
			if (!Directory.Exists(dir))
			{
				Directory.CreateDirectory(dir);
			}
			var ret = _application.EvalMapBasicCommand($"SaveLayoutItemCustomFrameFiles({layoutWindowId},{pageIndex}, {itemId},\"{dir}\" ) ");
			if (ret != null && Convert.ToString(ret) == "T")
			{
				string serializedFileName = GetfileName(dir, ".mlcf");
				string viewFileName = GetfileName(dir, ".xps");
				if (!string.IsNullOrEmpty(serializedFileName) && !string.IsNullOrEmpty(viewFileName))
				{
					templateFile.AppendLine(
						$"Add Custom Frame Position ({GetLayoutItemPositionX(layoutWindowId, itemId, pageIndex)}, {GetLayoutItemPositionY(layoutWindowId, itemId, pageIndex)}) {GetUnitsText()}");

					templateFile.AppendLine($"Width {GetLayoutItemWidth(layoutWindowId, itemId, pageIndex)} {GetUnitsText()}");
					templateFile.AppendLine($"Height {GetLayoutItemHeight(layoutWindowId, itemId, pageIndex)} {GetUnitsText()}");

					var brush = GetLayoutItemBrushString(layoutWindowId, itemId, pageIndex);
					if (brush != Constant.DefaultBrush)
					{
						templateFile.AppendLine(GetLayoutItemPenString(layoutWindowId, itemId, pageIndex));
						templateFile.AppendLine(GetLayoutItemBrushString(layoutWindowId, itemId, pageIndex));
					}
					templateFile.AppendLine(GetLayoutItemPriorityString(layoutWindowId, itemId, pageIndex));
					templateFile.AppendLine(GetLayoutItemNameText(layoutWindowId, itemId, pageIndex));
					string addinFileName = _application.EvalMapBasicCommand($"LayoutPageItemInfo({layoutWindowId}, {pageIndex}, {itemId}, 19)");

					if (!string.IsNullOrEmpty(addinFileName))
					{
						templateFile.AppendLine($"From File \"{Path.GetFileName(addinFileName)}\"");
					}
					string customdirectoryName = LayoutHelper.GetDirectoryName(dir);
					string metadataDirectoryName = LayoutHelper.GetDirectoryName(_templateFolderPath);
					string relativePath = metadataDirectoryName + "\\" + customdirectoryName;

					if (!string.IsNullOrEmpty(serializedFileName))
					{
						serializedFileName = Path.Combine(relativePath, serializedFileName);
						templateFile.AppendLine($"using \"{serializedFileName}\"");
					}
					if (!string.IsNullOrEmpty(viewFileName))
					{
						viewFileName = Path.Combine(relativePath, viewFileName);
						templateFile.AppendLine($"view \"{viewFileName}\"");
					}
				}
			}
		}
		/// <summary>
		/// Appends the layout item text.
		/// </summary>
		/// <param name="templateFile">The template file.</param>
		/// <param name="layoutWindowId">The layout window identifier.</param>
		/// <param name="itemId">The item identifier.</param>
		/// <param name="pageIndex">Index of the page.</param>
		private void AppendLayoutItemText(StringBuilder templateFile, int layoutWindowId, int itemId, int pageIndex)
		{
			/*Create Text
				[Into { Window window_id | Variable var_name } ] 
				 text_string
				(x1, y1)(x2, y2)
				[Font... ]
				[Spacing { 1.0 | 1.5 | 2.0 } ] 
				[Justify { Left | Center | Right } ] 
				[Angle text_angle]
			[Pen.... ]
			[Brush... ]
			[Priority n]
			[Name framename]*/

			var spacing = _application.EvalMapBasicCommand($"ObjectInfo(LayoutPageItemInfo({layoutWindowId}, {pageIndex}, {itemId}, 13),4)");
			var angle = _application.EvalMapBasicCommand($"LayoutPageItemInfo({layoutWindowId},{pageIndex},{itemId},18)");
			var justifyText = GetLayoutItemTextJustify(layoutWindowId, itemId, pageIndex);

			var penString = GetLayoutItemPenString(layoutWindowId, itemId, pageIndex);
			var brushString = GetLayoutItemBrushString(layoutWindowId, itemId, pageIndex);
			var priority = GetLayoutItemPriorityString(layoutWindowId, itemId, pageIndex);
			var text = _application.EvalMapBasicCommand($"ObjectInfo(LayoutPageItemInfo({layoutWindowId}, {pageIndex}, {itemId}, 13),3)");

			templateFile.AppendLine("Create Text");
			templateFile.AppendLine(2, "Into Window FrontWindow()");
			templateFile.AppendLine(2, $"\"{LayoutHelper.ConvertTextForTemplate(text)}\"");
			templateFile.AppendLine(2, GetLayoutItemShapePosition(layoutWindowId, itemId, pageIndex));
			templateFile.AppendLine(2, GetLayoutItemFontText(layoutWindowId, itemId, pageIndex));

			// do not add statement in case it is the default option
			if (!string.Equals(spacing, Constant.DefaultTextSpacing, StringComparison.InvariantCultureIgnoreCase))
				templateFile.AppendLine(2, $"Spacing {spacing}");

			if (!IsNullOrEmpty(justifyText) && !string.Equals(justifyText, Constant.DefaultTextJustify))
				templateFile.AppendLine(2, justifyText);

			if (!string.Equals(angle, Constant.DefaultAngle, StringComparison.InvariantCultureIgnoreCase))
				templateFile.AppendLine(2, $"Angle {angle}");

			if ((brushString != Constant.DefaultBrush) 
				|| (penString != Constant.DefaultPen))
			{
				templateFile.AppendLine(2, $"{penString} {brushString}");
			}
			templateFile.AppendLine(2, $"{ priority} { GetLayoutItemNameText(layoutWindowId, itemId, pageIndex)}");

		}

		/// <summary>
		/// Gets the metadata mb string.
		/// </summary>
		/// <param name="layoutWindowId">The layout window identifier.</param>
		/// <param name="itemId">The item identifier.</param>
		/// <param name="pageIndex">page index </param>
		/// <param name="key">The key.</param>
		/// <returns></returns>
		private string GetMetadataMapBasicString(int layoutWindowId, int pageIndex, int itemId, string key)
		{
			var val = LayoutHelper.GetFrameMetadataValue(_application, layoutWindowId, pageIndex, itemId, key);
			return string.IsNullOrEmpty(val) ? "" : $"{Constant.SetKey} \"{key}\" {Constant.To} \"{val}\" ";
		}
		/// <summary>
		/// Get layout itme name
		/// </summary>
		/// <param name="layoutWindowId">layout window id</param>
		/// <param name="itemId">Item id</param>
		/// <param name="pageIndex">Index of the page.</param>
		private string GetLayoutItemName(int layoutWindowId, int itemId, int pageIndex)
		{
			var frameName = _application.EvalMapBasicCommand($"LayoutPageItemInfo({layoutWindowId},{pageIndex},{itemId},14)");
			return frameName.ToString();
		}
		/// <summary>
		/// Gets the name text for layout item.
		/// </summary>
		/// <param name="layoutWindowId">The layout window identifier.</param>
		/// <param name="itemId">The item identifier.</param>
		/// <param name="pageIndex">Index of the page.</param>
		/// <returns></returns>
		private string GetLayoutItemNameText(int layoutWindowId, int itemId, int pageIndex)
		{
			string frameName = GetLayoutItemName(layoutWindowId, itemId, pageIndex);
			return string.IsNullOrEmpty(frameName) ? "" : $"Name \"{frameName}\"";
		}

		/// <summary>
		/// Gets the font text for layout item.
		/// </summary>
		/// <param name="layoutWindowId">The layout window identifier.</param>
		/// <param name="itemId">The item identifier.</param>
		/// <param name="pageIndex">Index of the page.</param>
		/// <returns></returns>
		private string GetLayoutItemFontText(int layoutWindowId, int itemId, int pageIndex)
		{
			return _application.EvalMapBasicCommand($"ObjectInfo(LayoutPageItemInfo({layoutWindowId}, {pageIndex}, {itemId}, 13),2)");
		}

		/// <summary>
		/// Appends the shape layout item.
		/// </summary>
		/// <param name="templateFile">The template file.</param>
		/// <param name="layoutWindowId">The layout window identifier.</param>
		/// <param name="itemId">The item identifier.</param>
		/// <param name="pageIndex">Index of the page.</param>
		private void AppendLayoutItemShape(StringBuilder templateFile, int layoutWindowId, int itemId, int pageIndex)
		{
			var shapeType =
				Convert.ToInt32(_application.EvalMapBasicCommand($"ObjectInfo(LayoutPageItemInfo({layoutWindowId}, {pageIndex}, {itemId}, 13),1)"));

			switch (shapeType)
			{
				case 2: // ellipse
					templateFile.AppendLine("Create Ellipse " + GetLayoutItemShapePosition(layoutWindowId, itemId, pageIndex));
					templateFile.AppendLine(2, GetLayoutItemBrushString(layoutWindowId, itemId, pageIndex));
					break;
				case 3: // line
					templateFile.AppendLine("Create Line " + GetLayoutItemShapePosition(layoutWindowId, itemId, pageIndex));
					break;
				case 4: // polyline 
					var numberOfPoints =
						Convert.ToInt32(_application.EvalMapBasicCommand($"ObjectInfo(LayoutPageItemInfo({layoutWindowId}, {pageIndex}, {itemId},13),20)"));
					templateFile.AppendLine($"Create Pline {numberOfPoints}");
					for (int i = 1; i <= numberOfPoints; i++)
					{
						var pointX =
							LayoutHelper.DoubleToMbString(
								_application.EvalMapBasicCommand($"ObjectNodeX(LayoutPageItemInfo({layoutWindowId}, {pageIndex}, {itemId},13),1,{i})"));
						var pointY =
							LayoutHelper.DoubleToMbString(
								_application.EvalMapBasicCommand($"ObjectNodeY(LayoutPageItemInfo({layoutWindowId}, {pageIndex}, {itemId},13),1,{i})"));
						templateFile.AppendLine(2, $"({pointX},{pointY})");
					}
					break;
				case 5: // point
					templateFile.AppendLine(
						$"Create Point {GetLayoutItemShapeLeftTopPosition(layoutWindowId,itemId, pageIndex)}");
					templateFile.AppendLine(2, 
						_application.EvalMapBasicCommand($"ObjectInfo(LayoutPageItemInfo({layoutWindowId}, {pageIndex}, {itemId}, 13),2)"));
					break;
				case 8: // rect
					templateFile.AppendLine("Create Rect " + GetLayoutItemShapePosition(layoutWindowId, itemId, pageIndex));
					templateFile.AppendLine(2, GetLayoutItemBrushString(layoutWindowId, itemId, pageIndex));
					break;
				case 9: // rounded rect
					var roundRadius =
						Math.Abs(LayoutHelper.StringToDouble(_application.EvalMapBasicCommand($"ObjectGeography(LayoutPageItemInfo({layoutWindowId}, {pageIndex}, {itemId}, 13), 5)")));
					templateFile.AppendLine("Create Roundrect " + GetLayoutItemShapePosition(layoutWindowId, itemId, pageIndex) + $" {LayoutHelper.DoubleToMbString(roundRadius, 3)}");
					templateFile.AppendLine(2, GetLayoutItemBrushString(layoutWindowId, itemId, pageIndex));
					break;
				case 7: // polygon/region 
					var numberOfPolygons = Convert.ToInt32(_application.EvalMapBasicCommand($"ObjectInfo(LayoutPageItemInfo({layoutWindowId}, {pageIndex}, {itemId}, 13),21)"));
					templateFile.AppendLine($"Create Region {numberOfPolygons}");
					numberOfPoints = Convert.ToInt32(_application.EvalMapBasicCommand($"ObjectInfo(LayoutPageItemInfo({layoutWindowId}, {pageIndex}, {itemId},13),20)"));
					templateFile.AppendLine(2, numberOfPoints.ToString());
					for (int i = 1; i <= numberOfPoints; i++)
					{
						var pointX =
							LayoutHelper.DoubleToMbString(
								_application.EvalMapBasicCommand($"ObjectNodeX(LayoutPageItemInfo({layoutWindowId}, {pageIndex}, {itemId},13),1,{i})"));
						var pointY =
							LayoutHelper.DoubleToMbString(
								_application.EvalMapBasicCommand($"ObjectNodeY(LayoutPageItemInfo({layoutWindowId}, {pageIndex}, {itemId},13),1,{i})"));
						templateFile.AppendLine(2, $"({pointX},{pointY})");
					}
					templateFile.AppendLine(GetLayoutItemBrushString(layoutWindowId, itemId, pageIndex));
					var centerX = LayoutHelper.DoubleToMbString(
						_application.EvalMapBasicCommand($"CentroidX(LayoutPageItemInfo({layoutWindowId}, {pageIndex}, {itemId},13))"));
					var centerY = LayoutHelper.DoubleToMbString(
						_application.EvalMapBasicCommand($"CentroidY(LayoutPageItemInfo({layoutWindowId}, {pageIndex}, {itemId},13))"));
					templateFile.AppendLine($"Center ({centerX},{centerY})");
					break;

				default:
					return;
			}

			if (shapeType != 5)
			{
				// don't write pen for symbols
				templateFile.AppendLine(2, GetLayoutItemPenString(layoutWindowId, itemId, pageIndex));
			}
			templateFile.AppendLine(2, GetLayoutItemPriorityString(layoutWindowId, itemId, pageIndex));
			var frameName = GetLayoutItemNameText(layoutWindowId, itemId, pageIndex);
			if (!string.IsNullOrEmpty(frameName))
				templateFile.AppendLine(2, frameName);
		}

		/// <summary>
		/// Appends the imgae layout item.
		/// </summary>
		/// <param name="templateFile">The template file.</param>
		/// <param name="layoutWindowId">The layout window identifier.</param>
		/// <param name="itemId">The item identifier.</param>
		/// <param name="pageIndex">Index of the page.</param>
		private void AppendLayoutItemImage(StringBuilder templateFile, int layoutWindowId, int itemId, int pageIndex)
		{
			var imageFileName = _application.EvalMapBasicCommand($"LayoutPageItemInfo({layoutWindowId},{pageIndex},{itemId},12)");
			AppendLayoutItemImage(templateFile, layoutWindowId, itemId, imageFileName, pageIndex);
		}
		/// <summary>
		/// Appends the layout item image.
		/// </summary>
		/// <param name="templateFile">The template file.</param>
		/// <param name="layoutWindowId">The layout window identifier.</param>
		/// <param name="itemId">The item identifier.</param>
		/// <param name="imageFilePath">The image file path.</param>
		/// <param name="pageIndex">Index of the page.</param>
		private void AppendLayoutItemImage(StringBuilder templateFile, int layoutWindowId, int itemId, string imageFilePath, int pageIndex)
		{
			string copiedImageFilePath = CopyImagetoImagesFolder(imageFilePath);
			if (!string.IsNullOrEmpty(copiedImageFilePath))
			{
				templateFile.AppendLine(
					$"Add Image Frame Position ({GetLayoutItemPositionX(layoutWindowId, itemId, pageIndex)}, {GetLayoutItemPositionY(layoutWindowId, itemId, pageIndex)}) {GetUnitsText()}");
				templateFile.AppendLine($"Width {GetLayoutItemWidth(layoutWindowId, itemId, pageIndex)} {GetUnitsText()}");
				templateFile.AppendLine($"Height {GetLayoutItemHeight(layoutWindowId, itemId, pageIndex)} {GetUnitsText()}");
				var brush = GetLayoutItemBrushString(layoutWindowId, itemId, pageIndex);
				if (brush != Constant.DefaultBrush)
				{
					templateFile.AppendLine(GetLayoutItemPenString(layoutWindowId, itemId, pageIndex));
					templateFile.AppendLine(GetLayoutItemBrushString(layoutWindowId, itemId, pageIndex));
				}
				var angle = _application.EvalMapBasicCommand($"LayoutPageItemInfo({layoutWindowId},{pageIndex},{itemId},18)");
				if (!string.Equals(angle, Constant.DefaultAngle, StringComparison.InvariantCultureIgnoreCase))
				{
					templateFile.AppendLine($"Angle {angle}");
				}
				templateFile.AppendLine(GetLayoutItemPriorityString(layoutWindowId, itemId, pageIndex));
				String name = GetLayoutItemNameText(layoutWindowId, itemId, pageIndex);
				if (!String.IsNullOrEmpty(name))
				{
					templateFile.AppendLine(name);
				}
				
				var imageFileName = Path.GetFileName(copiedImageFilePath);
				var imageFolderPath = LayoutHelper.GetImageFolderPath(_templateFolderPath);
				if (!string.IsNullOrEmpty(imageFileName) || !string.IsNullOrEmpty(imageFolderPath))
				{
					string path = imageFolderPath + "\\" + imageFileName;
					templateFile.AppendLine($"From File \"{path}\"");
				}
				else
				{
					templateFile.AppendLine($"From File \"{copiedImageFilePath}\"");
				}
			}
		}

		/// <summary>
		/// Appends the layout item empty.
		/// </summary>
		/// <param name="templateFile">The template file.</param>
		/// <param name="layoutWindowId">The layout window identifier.</param>
		/// <param name="itemId">The item identifier.</param>
		/// <param name="pageIndex">Index of the page.</param>
		private void AppendLayoutItemEmpty(StringBuilder templateFile, int layoutWindowId, int itemId, int pageIndex)
		{
			templateFile.AppendLine(GetCreateFrameMapBasic(layoutWindowId, itemId, pageIndex));

			string name = GetLayoutItemName(layoutWindowId, itemId, pageIndex);
			if (LayoutHelper.IsItemNameEmptyOrDefault(name))
			{
				// if empty frame has contentType = Image, then set name = Resource.Image_Frame_Tag
				if (LayoutHelper.GetFrameMetadataValue(_application, layoutWindowId, pageIndex, itemId, Constant.ContentType) == Constant.ContentTypeImage)
				{
					templateFile.AppendLine($" Name \"{Resource.Image_Frame_Tag}\"");
				}else
				{
					if(!String.IsNullOrEmpty(name))
					{
						templateFile.AppendLine(GetLayoutItemNameText(layoutWindowId, itemId, pageIndex));
					}
				}
			}
			else
			{
				templateFile.AppendLine(GetLayoutItemNameText(layoutWindowId, itemId, pageIndex));
			}

			// metadata
			string keyValue = GetMetadataMapBasicString(layoutWindowId, pageIndex, itemId, Constant.ContentType);
			if (keyValue != "")
			{
				templateFile.AppendLine($" { Constant.Metadata} {keyValue} ");
			}
		}
	
		

		/// <summary>
		/// Gets the create frame map basic.
		/// </summary>
		/// <param name="layoutWindowId">The layout window identifier.</param>
		/// <param name="itemId">The item identifier.</param>
		/// <param name="pageIndex">Index of the page.</param>
		/// <returns></returns>
		private string GetCreateFrameMapBasic(int layoutWindowId, int itemId, int pageIndex)
		{
			var pen = GetLayoutItemPenString(layoutWindowId, itemId, pageIndex);
			var brush = GetLayoutItemBrushString(layoutWindowId, itemId, pageIndex);
			var priority = GetLayoutItemPriorityString(layoutWindowId, itemId, pageIndex);

			return
				$"Create Frame {GetLayoutItemXy(layoutWindowId, itemId, pageIndex)} {pen} {brush} {priority}";
		}
		/// <summary>
		/// Get the next incremented name string for mappper, browser and legends
		/// </summary>
		/// <param name="layoutWindowId">Layout window id</param>
		/// <param name="itemType">Item type</param>
		/// <returns>return next incremented name</returns>
		private string GetNextNameString(int layoutWindowId, int itemType)
		{
			string itemName = null;
			switch(itemType)
			{
				case 1: //Mapper
					itemName = $"{Resource.Map}-{_mapIndex++}";
					while (_itemNamelist.Contains(itemName))
					{
						itemName = $"{Resource.Map}-{_mapIndex++}";
					}
					break;
				case 2: //Browser
					itemName = $"{Resource.Browser}-{_browserIndex++}";
					while (_itemNamelist.Contains(itemName))
					{
						itemName = $"{Resource.Browser}-{_browserIndex++}";
					}
					break;

				case 3: //Legend
					itemName = $"{Resource.Legend}-{_legendIndex++}";
					while (_itemNamelist.Contains(itemName))
					{
						itemName = $"{Resource.Legend}-{_legendIndex++}";
					}
					break;
				default:
					break;
			}
			if (!String.IsNullOrEmpty(itemName))
				_itemNamelist.Add(itemName);

			return itemName;
		}
		/// <summary>
		/// Get the incremented name text for browser, mappper and legends
		/// </summary>
		/// <param name="layoutWindowId">layoutWindowId</param>
		/// <param name="itemId">item id</param>
		/// <param name="pageIndex">Index of the page.</param>
		/// <returns>
		/// return name text else null
		/// </returns>
		private string GetIncrementedItemNameText(int layoutWindowId, int itemId, int pageIndex)
		{
			var sourceItemType = _application.EvalMapBasicCommand($"LayoutPageItemInfo({layoutWindowId},{pageIndex},{itemId},11)");
			if (sourceItemType == null)
				return null;
			string mbName = null;
			int srcItemType = Convert.ToInt32(sourceItemType);
			string name = GetLayoutItemName(layoutWindowId, itemId, pageIndex);
			if (LayoutHelper.IsItemNameEmptyOrDefault(name))
			{
				string itemName = GetNextNameString(layoutWindowId, srcItemType);
				if (!String.IsNullOrEmpty(itemName))
					mbName += $" Name \"{itemName}\" ";
			}
			else
			{
				mbName += $" {GetLayoutItemNameText(layoutWindowId, itemId, pageIndex)}";
			}
			return mbName;
		}
		/// <summary>
		/// Appends legends items
		/// </summary>
		/// <param name="templateFile">The template file.</param>
		/// <param name="layoutWindowId">The layout window identifier.</param>
		/// <param name="itemId">The item identifier.</param>
		/// <param name="pageIndex">Index of the page.</param>
		private void AppendLayoutItemLegends(StringBuilder templateFile, int layoutWindowId, int itemId, int pageIndex)
		{
			string mapbasic = GetCreateFrameMapBasic(layoutWindowId, itemId, pageIndex);

			string mbName = GetIncrementedItemNameText(layoutWindowId, itemId, pageIndex);
			if (!string.IsNullOrEmpty(mbName))
				mapbasic += mbName;


			mapbasic += $" Metadata Setkey \"{Constant.ContentType}\" To \"{Constant.ContentTypeLegend}\"";

			// Get the associated mapper and write out its unique-id in metadata
			var mapperId = LayoutHelper.GetLegendInfo(_application, layoutWindowId, itemId, 1, pageIndex);
			if (!String.IsNullOrEmpty(mapperId))
			{
				int mapId = Convert.ToInt32(mapperId);
				if (mapId != 0)
				{
					int mapperPageIndex = 0;
					int mapperFrameId = LayoutHelper.GetFrameIdFromMapWindowId(_application, layoutWindowId, mapId, out mapperPageIndex);
					if (mapperFrameId != -1)
					{
						string uniqueId = LayoutHelper.GetFrameUniqueId(_application, layoutWindowId, mapperFrameId, mapperPageIndex);
						if (!string.IsNullOrEmpty(uniqueId))
						{
							mapbasic += $" Setkey \"{Constant.MapperLegendAssociationId}\" To \"{uniqueId}\" ";
						}
					}
				}
			}
			// Write out the defaults in metadata
			string legendDefaultTitle = LayoutHelper.GetLegendInfo(_application, layoutWindowId, itemId, 9, pageIndex);
			string legendDefaultTitleFont = LayoutHelper.GetLegendInfo(_application, layoutWindowId, itemId, 10, pageIndex);
			legendDefaultTitleFont = legendDefaultTitleFont.Replace("\"","\\\"\"");

			string legendDefaultSubTitle = LayoutHelper.GetLegendInfo(_application, layoutWindowId, itemId, 11, pageIndex);
			string legendDefaultSubtitleFont = LayoutHelper.GetLegendInfo(_application, layoutWindowId, itemId, 12, pageIndex);
			legendDefaultSubtitleFont = legendDefaultSubtitleFont.Replace("\"", "\\\"\"");
			string legendDefaultStyle = LayoutHelper.GetLegendInfo(_application, layoutWindowId, itemId, 13, pageIndex);
			string legendDefaultStyleFont = LayoutHelper.GetLegendInfo(_application, layoutWindowId, itemId, 14, pageIndex);
			legendDefaultStyleFont = legendDefaultStyleFont.Replace("\"", "\\\"\"");
			string legendDefaultAutoFontSize = LayoutHelper.GetLegendInfo(_application, layoutWindowId, itemId, 15, pageIndex);

			string legendDefaultLineWidth = LayoutHelper.GetLegendInfo(_application, layoutWindowId, itemId, 5, pageIndex);
			string legendDefaultRegionWidth = LayoutHelper.GetLegendInfo(_application, layoutWindowId, itemId, 6, pageIndex);
			string legendDefaultRegionHeight = LayoutHelper.GetLegendInfo(_application, layoutWindowId, itemId, 7, pageIndex);

			if (!String.IsNullOrEmpty(legendDefaultTitle))
			{
				mapbasic += $"Setkey \"{Constant.LegendDefaultTitle}\" To \"{legendDefaultTitle}\" ";
			}
			if (!String.IsNullOrEmpty(legendDefaultTitleFont))
			{
				mapbasic += $"Setkey \"{Constant.LegendDefaultTitleFont}\" To \"{legendDefaultTitleFont}\" ";
			}
			if (!String.IsNullOrEmpty(legendDefaultSubTitle))
			{
				mapbasic += $"Setkey \"{Constant.LegendDefaultSubTitle}\" To \"{legendDefaultSubTitle}\" ";
			}
			if (!String.IsNullOrEmpty(legendDefaultSubtitleFont))
			{
				mapbasic += $"Setkey \"{Constant.LegendDefaultSubtitleFont}\" To \"{legendDefaultSubtitleFont}\" ";
			}
			if (!String.IsNullOrEmpty(legendDefaultStyle))
			{
				mapbasic += $"Setkey \"{Constant.LegendDefaultStyle}\" To \"{legendDefaultStyle}\" ";
			}
			if (!String.IsNullOrEmpty(legendDefaultStyleFont))
			{
				mapbasic += $"Setkey \"{Constant.LegendDefaultStyleFont}\" To \"{legendDefaultStyleFont}\" ";
			}
			if (!String.IsNullOrEmpty(legendDefaultAutoFontSize))
			{
				mapbasic += $"Setkey \"{Constant.LegendDefaultAutoFontSize}\" To \"{legendDefaultAutoFontSize}\" ";
			}
			if (!String.IsNullOrEmpty(legendDefaultLineWidth))
			{
				mapbasic += $"Setkey \"{Constant.LegendDefaultLineWidth}\" To \"{legendDefaultLineWidth}\" ";
			}
			if (!String.IsNullOrEmpty(legendDefaultRegionWidth))
			{
				mapbasic += $"Setkey \"{Constant.LegendDefaultRegionWidth}\" To \"{legendDefaultRegionWidth}\" ";
			}
			if (!String.IsNullOrEmpty(legendDefaultRegionHeight))
			{
				mapbasic += $"Setkey \"{Constant.LegendDefaultRegionHeight}\" To \"{legendDefaultRegionHeight}\" ";
			}
			string unit = GetUnit();
			if (!String.IsNullOrEmpty(unit))
			{
				mapbasic += $"Setkey \"{Constant.LegendDefaultUnit}\" To \"{unit}\" ";
			}
			templateFile.AppendLine(mapbasic);
		}
		/// <summary>
		/// Appends the mapper layout item.
		/// </summary>
		/// <param name="templateFile">The template file.</param>
		/// <param name="layoutWindowId">The layout window identifier.</param>
		/// <param name="itemId">The item identifier.</param>
		/// <param name="pageIndex">Index of the page.</param>
		private void AppendLayoutItemMapper(StringBuilder templateFile, int layoutWindowId, int itemId, int pageIndex)
		{
			string mapbasic = GetCreateFrameMapBasic(layoutWindowId, itemId, pageIndex);
			string mbName = GetIncrementedItemNameText(layoutWindowId, itemId, pageIndex);
			if (!string.IsNullOrEmpty(mbName))
				mapbasic += mbName;

			mapbasic += $" Metadata Setkey \"{Constant.ContentType}\" To \"{Constant.ContentTypeMapper}\"";
			mapbasic += $" Setkey \"{Constant.MapperLegendAssociationId }\" To \"{LayoutHelper.GetFrameUniqueId(_application,layoutWindowId,itemId, pageIndex)}\"";
			templateFile.AppendLine(mapbasic);
		}

		/// <summary>
		/// Appends the browser layout item.
		/// </summary>
		/// <param name="templateFile">The template file.</param>
		/// <param name="layoutWindowId">The layout window identifier.</param>
		/// <param name="itemId">The item identifier.</param>
		/// <param name="pageIndex">Index of the page.</param>
		private void AppendLayoutItemBrowser(StringBuilder templateFile, int layoutWindowId, int itemId, int pageIndex)
		{
			string mapbasic = GetCreateFrameMapBasic(layoutWindowId, itemId, pageIndex);
			string mbName = GetIncrementedItemNameText(layoutWindowId, itemId, pageIndex);
			if (!string.IsNullOrEmpty(mbName))
				mapbasic += mbName;

			mapbasic += $" Metadata Setkey \"{Constant.ContentType}\" To \"{Constant.ContentTypeBrowser}\" ";

			templateFile.AppendLine(mapbasic);
		}
		/// <summary>
		/// Get unit
		/// </summary>
		/// <returns>unit</returns>
		private string GetUnit()
		{
			var unit = _application.EvalMapBasicCommand("SessionInfo(4)");
			return unit;
		}
		/// <summary>
		/// Gets the units text.
		/// </summary>
		private string GetUnitsText()
		{
			string unit = GetUnit();
			if(!string.IsNullOrEmpty(unit))
				return $"Units \"{unit}\"";
			else
			{
				return "";
			}
		}

		/// <summary>
		/// Gets the brush string of layout item .
		/// </summary>
		/// <param name="layoutWindowId">The layout window identifier.</param>
		/// <param name="itemId">The item identifier.</param>
		/// <param name="pageIndex">Index of the page.</param>
		/// <returns></returns>
		private string GetLayoutItemBrushString(int layoutWindowId, int itemId, int pageIndex)
		{
			return _application.EvalMapBasicCommand($"LayoutPageItemInfo({layoutWindowId}, {pageIndex}, {itemId}, 16)");
		}

		/// <summary>
		/// Gets the pen string of layout item .
		/// </summary>
		/// <param name="layoutWindowId">The layout window identifier.</param>
		/// <param name="itemId">The item identifier.</param>
		/// <param name="pageIndex">Index of the page.</param>
		/// <returns></returns>
		private string GetLayoutItemPenString(int layoutWindowId, int itemId, int pageIndex)
		{
			return _application.EvalMapBasicCommand($"LayoutPageItemInfo({layoutWindowId}, {pageIndex}, {itemId}, 15)");
		}

		/// <summary>
		/// Gets the priority string of layout item .
		/// </summary>
		/// <param name="layoutWindowId">The layout window identifier.</param>
		/// <param name="itemId">The item identifier.</param>
		/// <param name="pageIndex">Index of the page.</param>
		/// <returns></returns>
		private string GetLayoutItemPriorityString(int layoutWindowId, int itemId, int pageIndex)
		{
			return "Priority " + Convert.ToInt32(_application.EvalMapBasicCommand($"LayoutPageItemInfo({layoutWindowId},{pageIndex},{itemId},17)"));
		}

		/// <summary>
		/// Gets the justify text for layout item.
		/// </summary>
		/// <param name="layoutWindowId">The layout window identifier.</param>
		/// <param name="itemId">The item identifier.</param>
		/// <param name="pageIndex">Index of the page.</param>
		/// <returns></returns>
		private string GetLayoutItemTextJustify(int layoutWindowId, int itemId, int pageIndex)
		{
			string justifyText = "";
			var justify = Convert.ToInt32(_application.EvalMapBasicCommand($"ObjectInfo(LayoutPageItemInfo({layoutWindowId}, {pageIndex}, {itemId}, 13),5)"));
			switch (justify)
			{
				case 0:
					justifyText = "Left";
					break;
				case 1:
					justifyText = "Center";
					break;
				case 2:
					justifyText = "Right";
					break;
			}

			return string.IsNullOrEmpty(justifyText) ? "" : "justify " + justifyText;
		}

		/// <summary>
		/// Gets the X corrdinate of layout item.
		/// </summary>
		/// <param name="layoutWindowId">The layout window identifier.</param>
		/// <param name="itemId">The item identifier.</param>
		/// <param name="pageIndex">Index of the page.</param>
		/// <returns></returns>
		private string GetLayoutItemPositionX(int layoutWindowId, int itemId, int pageIndex)
		{
			var xPos = _application.EvalMapBasicCommand($"LayoutPageItemInfo({layoutWindowId},{pageIndex},{itemId},1)");
			if(xPos != null)
			{
				return LayoutHelper.DoubleToMbString(xPos);
			}
			return null;
		}

		/// <summary>
		/// Gets the Y coordinate of layout item.
		/// </summary>
		/// <param name="layoutWindowId">The layout window identifier.</param>
		/// <param name="itemId">The item identifier.</param>
		/// <param name="pageIndex">Index of the page.</param>
		/// <returns></returns>
		private string GetLayoutItemPositionY(int layoutWindowId, int itemId, int pageIndex)
		{
			var yPos = _application.EvalMapBasicCommand($"LayoutPageItemInfo({layoutWindowId},{pageIndex},{itemId},2)");
			if (yPos != null)
			{
				return LayoutHelper.DoubleToMbString(yPos);
			}
			return null;
		}

		/// <summary>
		/// Gets the width of the layout item.
		/// </summary>
		/// <param name="layoutWindowId">The layout window identifier.</param>
		/// <param name="itemId">The item identifier.</param>
		/// <param name="pageIndex">Index of the page.</param>
		/// <returns></returns>
		private string GetLayoutItemWidth(int layoutWindowId, int itemId, int pageIndex)
		{
			var width = _application.EvalMapBasicCommand($"LayoutPageItemInfo({layoutWindowId},{pageIndex},{itemId},3)");
			if (width != null)
			{
				return LayoutHelper.DoubleToMbString(width);
			}
			return null;
		}

		/// <summary>
		/// Gets the height of the layout item.
		/// </summary>
		/// <param name="layoutWindowId">The layout window identifier.</param>
		/// <param name="itemId">The item identifier.</param>
		/// <param name="pageIndex">Index of the page.</param>
		/// <returns></returns>
		private string GetLayoutItemHeight(int layoutWindowId, int itemId, int pageIndex)
		{
			var height = _application.EvalMapBasicCommand($"LayoutPageItemInfo({layoutWindowId},{pageIndex},{itemId},4)");
			if (height != null)
			{
				return LayoutHelper.DoubleToMbString(height);
			}
			return null;
		}

		/// <summary>
		/// Gets the (X1,Y1) (X2,Y2) statement for layout item.
		/// </summary>
		/// <param name="layoutWindowId">The layout window identifier.</param>
		/// <param name="itemId">The item identifier.</param>
		/// <param name="pageIndex">Index of the page.</param>
		/// <returns></returns>
		private string GetLayoutItemXy(int layoutWindowId, int itemId, int pageIndex)
		{
			var x1 = _application.EvalMapBasicCommand($"LayoutPageItemInfo({layoutWindowId},{pageIndex},{itemId},1)");
			var y1 = _application.EvalMapBasicCommand($"LayoutPageItemInfo({layoutWindowId},{pageIndex},{itemId},2)");
			var width = _application.EvalMapBasicCommand($"LayoutPageItemInfo({layoutWindowId},{pageIndex},{itemId},3)");
			var height = _application.EvalMapBasicCommand($"LayoutPageItemInfo({layoutWindowId},{pageIndex},{itemId},4)");
			var x2 = LayoutHelper.StringToDouble(x1) + LayoutHelper.StringToDouble(width);
			var y2 = LayoutHelper.StringToDouble(y1) + LayoutHelper.StringToDouble(height);

			var x1Mb = LayoutHelper.DoubleToMbString(x1);
			var y1Mb = LayoutHelper.DoubleToMbString(y1);
			var x2Mb = LayoutHelper.DoubleToMbString(x2);
			var y2Mb = LayoutHelper.DoubleToMbString(y2);

			return $"({x1Mb},{y1Mb}) ({x2Mb}, {y2Mb})";
		}

		/// <summary>
		/// Gets the (X1,Y1)statement for layout item.
		/// </summary>
		/// <param name="layoutWindowId">The layout window identifier.</param>
		/// <param name="itemId">The item identifier.</param>
		/// <param name="pageIndex">Index of the page.</param>
		/// <returns></returns>
		private string GetLayoutItemShapeLeftTopPosition(int layoutWindowId, int itemId, int pageIndex)
		{
			var x1 = _application.EvalMapBasicCommand($"ObjectGeography(LayoutPageItemInfo({layoutWindowId},{pageIndex},{itemId},13), 1)");
			var y1 = _application.EvalMapBasicCommand($"ObjectGeography(LayoutPageItemInfo({layoutWindowId},{pageIndex},{itemId},13), 2)");

			var x1Mb = LayoutHelper.DoubleToMbString(x1);
			var y1Mb = LayoutHelper.DoubleToMbString(y1);

			return $"({x1Mb},{y1Mb})";
		}


		/// <summary>
		/// Gets the (X1,Y1) (X2,Y2) statement for layout Shape item.
		/// </summary>
		/// <param name="layoutWindowId">The layout window identifier.</param>
		/// <param name="itemId">The item identifier.</param>
		/// <param name="pageIndex">Index of the page.</param>
		/// <returns></returns>
		private string GetLayoutItemShapePosition(int layoutWindowId, int itemId, int pageIndex)
		{
			var x1 = _application.EvalMapBasicCommand($"ObjectGeography(LayoutPageItemInfo({layoutWindowId},{pageIndex},{itemId},13), 1)");
			var y1 = _application.EvalMapBasicCommand($"ObjectGeography(LayoutPageItemInfo({layoutWindowId},{pageIndex},{itemId},13), 2)");
			var x2 = _application.EvalMapBasicCommand($"ObjectGeography(LayoutPageItemInfo({layoutWindowId},{pageIndex},{itemId},13), 3)");
			var y2 = _application.EvalMapBasicCommand($"ObjectGeography(LayoutPageItemInfo({layoutWindowId},{pageIndex},{itemId},13), 4)");

			var x1Mb = LayoutHelper.DoubleToMbString(x1);
			var y1Mb = LayoutHelper.DoubleToMbString(y1);
			var x2Mb = LayoutHelper.DoubleToMbString(x2);
			var y2Mb = LayoutHelper.DoubleToMbString(y2);

			return $"({x1Mb},{y1Mb}) ({x2Mb}, {y2Mb})";
		}

		#endregion
	}
}
