using System.Runtime.Serialization;
using System.IO;

namespace wijmoSample1.Models.FileExplorer
{
	[DataContract]
	public class FileExplorerItem : IItemOperationResult
	{
		/// <summary>
		/// Create a FileExplorerItem with the specified path.
		/// </summary>
		public FileExplorerItem(string path)
		{
			var localPath = Helper.MapPath(path);
			if (Helper.IsDirectory(localPath))
			{
				var dirInfo = new DirectoryInfo(localPath);
				InitByDirInfo(dirInfo);
			}
			else
			{
				var fileInfo = new FileInfo(localPath);
				InitByDirInfo(fileInfo);

			}
			Path = path;
		}

		/// <summary>
		/// Create a FileExplorerItem with the specified parent path and DirectoryInfo.
		/// </summary>
		public FileExplorerItem(string virtualParentPath, DirectoryInfo dirInfo)
		{
			InitByDirInfo(dirInfo);
			Path = System.IO.Path.Combine(virtualParentPath, Name).Replace("\\", "/");
		}

		/// <summary>
		/// Create a FileExplorerItem with the specified parent path and FileInfo.
		/// </summary>
		public FileExplorerItem(string virtualParentPath, FileInfo fileInfo)
		{
			InitByDirInfo(fileInfo);
			Path = System.IO.Path.Combine(virtualParentPath, Name).Replace("\\", "/");
		}

		private void InitByDirInfo(FileInfo fileInfo)
		{
			Name = fileInfo.Name;
			NameWithoutExtension = System.IO.Path.GetFileNameWithoutExtension(fileInfo.FullName);
			Size = fileInfo.Length;
		}

		private void InitByDirInfo(DirectoryInfo dirInfo)
		{
			IsFolder = true;
			HasChildren = dirInfo.GetFileSystemInfos().Length > 0;
			HasSubFolders = dirInfo.GetDirectories().Length > 0;
			Name = dirInfo.Name;
			NameWithoutExtension = dirInfo.Name;
		}

		/// <summary>
		/// Gets current item's path.
		/// </summary>
		[DataMember(Name = "path")]
		public string Path { get; private set; }

		internal string NameWithoutExtension { get; private set; }

		internal string Name { get; private set; }

		/// <summary>
		/// Gets whether current item has subfolders.
		/// </summary>
		[DataMember(Name = "hasSubFolders", EmitDefaultValue = false)]
		public bool? HasSubFolders { get; private set; }

		/// <summary>
		/// Gets whether current item has children.
		/// </summary>
		[DataMember(Name = "hasChildren", EmitDefaultValue = false)]
		public bool? HasChildren { get; private set; }

		/// <summary>
		/// Gets whether current item is a folder.
		/// </summary>
		[DataMember(Name = "isFolder")]
		public bool IsFolder { get; private set; }

		/// <summary>
		/// Gets whether current item's size.
		/// </summary>
		[DataMember(Name = "size", EmitDefaultValue = false)]
		public long? Size { get; private set; }
	}
}