using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.IO;
using System.Text.RegularExpressions;

namespace wijmoSample1.Models.FileExplorer
{
	public static class Helper
	{
		private const char FolderSeparator = '/';

		public static int ComparisonWithName(FileExplorerItem a, FileExplorerItem b)
		{
			var aNameWithoutExtension = a.NameWithoutExtension;
			var bNameWithoutExtension = b.NameWithoutExtension;

			if (string.Equals(aNameWithoutExtension, bNameWithoutExtension, StringComparison.OrdinalIgnoreCase))
			{
				return String.Compare(a.Name, b.Name, StringComparison.OrdinalIgnoreCase);
			}

			var numRegex = new Regex("\\d+");
			var matches = numRegex.Matches(aNameWithoutExtension + bNameWithoutExtension).Cast<Match>().ToList();
			if (matches.Any())
			{
				var maxLen = matches.Max(num => num.Length);
				aNameWithoutExtension = numRegex.Replace(aNameWithoutExtension, (m => m.Value.PadLeft(maxLen, '0')));
				bNameWithoutExtension = numRegex.Replace(bNameWithoutExtension, (m => m.Value.PadLeft(maxLen, '0')));
			}

			return String.Compare(aNameWithoutExtension, bNameWithoutExtension, StringComparison.OrdinalIgnoreCase);
		}


		public static string MapPath(string path)
		{
			return HttpContext.Current.Server.MapPath(path);
		}

		public static bool IsDirectory(string path)
		{
			return (File.GetAttributes(path) & FileAttributes.Directory) == FileAttributes.Directory;
		}

		public static FileExplorerItem CreateFileExplorerItem(string parentPath, string localPath)
		{
			if (IsDirectory(localPath))
			{
				var dirInfo = new DirectoryInfo(localPath);
				return new FileExplorerItem(parentPath, dirInfo);
			}

			var fileInfo = new FileInfo(localPath);
			return new FileExplorerItem(parentPath, fileInfo);
		}

		public static bool IsAncestorFolder(string mayAncestorPath, string mayDescendantPath)
		{
			return mayDescendantPath.IndexOf(EnsureFolderSeparator(mayAncestorPath), StringComparison.OrdinalIgnoreCase) == 0;
		}

		public static string EnsureFolderSeparator(string path)
		{
			return path[path.Length - 1] == FolderSeparator ? path : path + FolderSeparator;
		}
	}
}