aboutsummaryrefslogtreecommitdiff
path: root/MediaBrowser.Controller/Sorting/BaseItemComparer.cs
blob: 94c16775d0240fe959e9ae6ea48e531ed2aad042 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
using MediaBrowser.Controller.Entities;
using MediaBrowser.Model.Logging;
using System;
using System.Collections.Generic;

namespace MediaBrowser.Controller.Sorting {
    /// <summary>
    /// Class BaseItemComparer
    /// </summary>
    public class BaseItemComparer : IComparer<BaseItem> {
        /// <summary>
        /// The _order
        /// </summary>
        private readonly SortOrder _order;
        /// <summary>
        /// The _property name
        /// </summary>
        private readonly string _propertyName;
        /// <summary>
        /// The _compare culture
        /// </summary>
        private readonly StringComparison _compareCulture = StringComparison.CurrentCultureIgnoreCase;

        /// <summary>
        /// Gets or sets the logger.
        /// </summary>
        /// <value>The logger.</value>
        private ILogger Logger { get; set; }

        /// <summary>
        /// Initializes a new instance of the <see cref="BaseItemComparer" /> class.
        /// </summary>
        /// <param name="order">The order.</param>
        /// <param name="logger">The logger.</param>
        public BaseItemComparer(SortOrder order, ILogger logger) {
            _order = order;
            Logger = logger;
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="BaseItemComparer" /> class.
        /// </summary>
        /// <param name="order">The order.</param>
        /// <param name="compare">The compare.</param>
        /// <param name="logger">The logger.</param>
        public BaseItemComparer(SortOrder order, StringComparison compare, ILogger logger)
        {
            _order = order;
            _compareCulture = compare;
            Logger = logger;
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="BaseItemComparer" /> class.
        /// </summary>
        /// <param name="property">The property.</param>
        /// <param name="logger">The logger.</param>
        public BaseItemComparer(string property, ILogger logger)
        {
            _order = SortOrder.Custom;
            _propertyName = property;
            Logger = logger;
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="BaseItemComparer" /> class.
        /// </summary>
        /// <param name="property">The property.</param>
        /// <param name="compare">The compare.</param>
        /// <param name="logger">The logger.</param>
        public BaseItemComparer(string property, StringComparison compare, ILogger logger)
        {
            _order = SortOrder.Custom;
            _propertyName = property;
            _compareCulture = compare;
            Logger = logger;
        }

        #region IComparer<BaseItem> Members

        /// <summary>
        /// Compares the specified x.
        /// </summary>
        /// <param name="x">The x.</param>
        /// <param name="y">The y.</param>
        /// <returns>System.Int32.</returns>
        public int Compare(BaseItem x, BaseItem y) {
            int compare = 0;

            switch (_order) {

                case SortOrder.Date:
                    compare = -x.DateCreated.CompareTo(y.DateCreated);
                    break;

                case SortOrder.Year:

                    var xProductionYear = x.ProductionYear ?? 0;
                    var yProductionYear = y.ProductionYear ?? 0;


                    compare = yProductionYear.CompareTo(xProductionYear); 
                    break;

                case SortOrder.Rating:

                    var xRating = x.CommunityRating ?? 0;
                    var yRating = y.CommunityRating ?? 0;

                    compare = yRating.CompareTo(xRating);
                    break;

                case SortOrder.Runtime:
                    var xRuntime = x.RunTimeTicks ?? 0;
                    var yRuntime = y.RunTimeTicks ?? 0;

                    compare = xRuntime.CompareTo(yRuntime);
                    break;

                case SortOrder.Custom:

                    Logger.Debug("Sorting on custom field " + _propertyName);
                    var yProp = y.GetType().GetProperty(_propertyName);
                    var xProp = x.GetType().GetProperty(_propertyName);
                    if (yProp == null || xProp == null) break;
                    var yVal = yProp.GetValue(y, null);
                    var xVal = xProp.GetValue(x,null);
                    if (yVal == null && xVal == null) break;
                    if (yVal == null) return 1;
                    if (xVal == null) return -1;
                    compare = String.Compare(xVal.ToString(), yVal.ToString(),_compareCulture);
                    break;

                default:
                    compare = 0;
                    break;
            }

            if (compare == 0) {

                var name1 = x.SortName ?? x.Name ?? "";
                var name2 = y.SortName ?? y.Name ?? "";

                //if (Config.Instance.EnableAlphanumericSorting)
                    compare = AlphaNumericCompare(name1, name2,_compareCulture);
                //else
                //    compare = String.Compare(name1,name2,_compareCulture);
            }

            return compare;
        }


        #endregion

        /// <summary>
        /// Alphas the numeric compare.
        /// </summary>
        /// <param name="s1">The s1.</param>
        /// <param name="s2">The s2.</param>
        /// <param name="compareCulture">The compare culture.</param>
        /// <returns>System.Int32.</returns>
        private int AlphaNumericCompare(string s1, string s2, StringComparison compareCulture) {
            // http://dotnetperls.com/Content/Alphanumeric-Sorting.aspx

            int len1 = s1.Length;
            int len2 = s2.Length;
            int marker1 = 0;
            int marker2 = 0;

            // Walk through two the strings with two markers.
            while (marker1 < len1 && marker2 < len2) {
                char ch1 = s1[marker1];
                char ch2 = s2[marker2];

                // Some buffers we can build up characters in for each chunk.
                var space1 = new char[len1];
                var loc1 = 0;
                var space2 = new char[len2];
                var loc2 = 0;

                // Walk through all following characters that are digits or
                // characters in BOTH strings starting at the appropriate marker.
                // Collect char arrays.
                do {
                    space1[loc1++] = ch1;
                    marker1++;

                    if (marker1 < len1) {
                        ch1 = s1[marker1];
                    } else {
                        break;
                    }
                } while (char.IsDigit(ch1) == char.IsDigit(space1[0]));

                do {
                    space2[loc2++] = ch2;
                    marker2++;

                    if (marker2 < len2) {
                        ch2 = s2[marker2];
                    } else {
                        break;
                    }
                } while (char.IsDigit(ch2) == char.IsDigit(space2[0]));

                // If we have collected numbers, compare them numerically.
                // Otherwise, if we have strings, compare them alphabetically.
                var str1 = new string(space1);
                var str2 = new string(space2);
                
                var result = 0;

                //biggest int - 2147483647
                if (char.IsDigit(space1[0]) && char.IsDigit(space2[0]) /*&& str1.Length < 10 && str2.Length < 10*/) //this assumed the entire string was a number...
                {
                    int thisNumericChunk;
                    var isValid = false;

                    if (int.TryParse(str1.Substring(0, str1.Length > 9 ? 10 : str1.Length), out thisNumericChunk))
                    {
                        int thatNumericChunk;
                        
                        if (int.TryParse(str2.Substring(0, str2.Length > 9 ? 10 : str2.Length), out thatNumericChunk))
                        {
                            isValid = true;
                            result = thisNumericChunk.CompareTo(thatNumericChunk);
                        }
                    }
                    
                    if (!isValid)
                    {
                        Logger.Error("Error comparing numeric strings: " + str1 + "/" + str2);
                        result = String.Compare(str1, str2, compareCulture);
                    }
                    
                } else {
                    result = String.Compare(str1,str2,compareCulture);
                }

                if (result != 0) {
                    return result;
                }
            }
            return len1 - len2;
        }
    }
}