Fix for missing directories
[pithos-ms-client] / trunk / Pithos.Client.WPF / Utils / EnumerableExtensions.cs
1 using System;
2 using System.Collections;
3 using System.Collections.Generic;
4 using System.Linq;
5 using System.Linq.Expressions;
6 using System.Text;
7 using System.Text.RegularExpressions;
8 using Pithos.Client.WPF.SelectiveSynch;
9 using Pithos.Core;
10 using Pithos.Interfaces;
11
12 namespace Pithos.Client.WPF.Utils
13 {
14     public static class EnumerableExtensions
15     {
16         public static IEnumerable<T> Slice<T>(this IEnumerable<T> collection, int start, int end)
17         {
18             int index = 0;
19             int count = 0;
20
21             if (collection == null)
22                 throw new ArgumentNullException("collection");
23
24             // Optimise item count for ICollection interfaces.
25             if (collection is ICollection<T>)
26                 count = ((ICollection<T>)collection).Count;
27             else if (collection is ICollection)
28                 count = ((ICollection)collection).Count;
29             else
30             {
31                 count = collection.Count();
32             }
33
34             // Get start/end indexes, negative numbers start at the end of the collection.
35             if (start < 0)
36                 start += count;
37
38             if (end < 0)
39                 end += count;
40
41             foreach (var item in collection)
42             {
43                 if (index >= end)
44                     yield break;
45
46                 if (index >= start)
47                     yield return item;
48
49                 ++index;
50             }
51         }
52
53         public static IEnumerable<Node<T>> ToTree<TSource,T>(this IEnumerable<TSource> enumerable,Func<TSource,string> pathFunc,Func<TSource,T> valueFunc,string delimiter="/")
54         {
55             var orderedItems=enumerable.OrderBy(pathFunc);
56             var lookups = new Dictionary<string,Node<T>>();
57             var nodes = new List<Node<T>>();
58             foreach (var item in orderedItems)
59             {
60                 var path = pathFunc(item);
61                 var value = valueFunc(item);
62                 var newNode = new Node<T> { Path = path,Data=value };
63                 lookups[path] = newNode;
64
65                 var lastIndex = path.LastIndexOf(delimiter, StringComparison.Ordinal);
66                 var upTo = lastIndex < 0 ? path.Length - 1 : lastIndex;
67                 var parentPath = path.Substring(0, upTo);              
68   
69                 Node<T> parent;
70                 if (lookups.TryGetValue(parentPath, out parent))
71                 {
72                     parent.Children.Add(newNode);   
73                     parent.Children.Sort((x,y)=>String.CompareOrdinal(x.Path, y.Path));
74                 }
75                 else
76                     nodes.Add(newNode);
77
78             }
79             return nodes;
80         }
81
82         public static List<DirectoryRecord> ToTree(this IEnumerable<ObjectInfo> enumerable)
83         {
84             //Order the items to ensure that children always come after their parents
85             var orderedItems=enumerable.OrderBy(o=>o.Uri.ToString());
86             //Each item is stored in lookups
87             var lookups = new Dictionary<string,DirectoryRecord>();
88             
89             //RootNodes contains only the root nodes
90             var rootNodes = new List<DirectoryRecord>();            
91
92             foreach (var item in orderedItems)
93             {
94                 var path = item.Uri.ToString();
95                 //Calculate the parent path
96                 var parentPath = GetParentPath(path);
97                 var parentName = GetParentPath(item.Name);
98                 DirectoryRecord parent;
99                 DirectoryRecord newNode;
100
101                 //Dont't add files
102                 if (!item.IsDirectory)
103                 {
104                     //But check to ensure that we DO have it's parent on record
105                     //It it exist
106                     if (lookups.TryGetValue(parentPath, out parent))
107                     {
108                         //Just continue
109                         continue;
110                     }
111                     //If the item is directly below its parent container, there is no path to add
112                     if (String.IsNullOrWhiteSpace(parentName))
113                         continue;
114                     //Otherwise we need to add it, because it is missing from the list
115                     //Store each item using its current path
116                     newNode = new DirectoryRecord { DisplayName = parentPath.Split('/').Last(), 
117                         ObjectInfo = new ObjectInfo{Account=item.Account,Container=item.Container,Name=parentPath,Content_Type="application/directory"}};
118                 }
119                 else
120                 {
121                     //Store each item using its current path
122                     newNode = new DirectoryRecord {DisplayName = item.Name.Split('/').Last(), ObjectInfo = item};
123                 }
124                 AddNode(rootNodes, parentPath, path, lookups, newNode);
125             }
126             return rootNodes;
127         }
128
129         private static void AddNode(List<DirectoryRecord> rootNodes, string parentPath, string path, Dictionary<string, DirectoryRecord> lookups, DirectoryRecord newNode)
130         {
131             DirectoryRecord parent;
132             lookups[path] = newNode;
133
134
135             //Does a parent item exist? 
136             if (lookups.TryGetValue(parentPath, out parent))
137             {
138                 //If so, add the current item under its parent
139                 parent.Directories.Add(newNode);
140                 parent.Directories.Sort((x, y) => String.CompareOrdinal(x.Uri.ToString(), y.Uri.ToString()));
141             }
142             else
143                 //Otherwise add it to the list of root nodes
144                 rootNodes.Add(newNode);
145         }
146
147         private static string GetParentPath(string path)
148         {            
149             var lastIndex = path.LastIndexOf("/", StringComparison.Ordinal);
150             if (lastIndex < 0)
151                 return null;
152             var parentPath = path.Substring(0, lastIndex);
153             return parentPath;
154         }
155
156         static readonly Regex PascalCaseRegex = new Regex("[a-z][A-Z]", RegexOptions.Compiled);        
157         public static string Name(this  Enum value)
158         {
159             var name = Enum.GetName(value.GetType(), value);            
160             return PascalCaseRegex.Replace(name, m => m.Value[0] + " " + char.ToLower(m.Value[1]));            
161         }
162     }
163 }