vb6runtime 0.2.0

VB6 runtime library - value system, type conversions, and standard library implementations
Documentation
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
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
//! ## `Filter` Function
//!
//! Returns a zero-based array containing a subset of a string array based on specified filter criteria.
//!
//! ## Syntax
//!
//! ```text
//! Filter(sourcearray, match[, include[, compare]])
//! ```
//!
//! ## Parameters
//!
//! - **sourcearray**: Required. One-dimensional array of strings to be searched.
//! - **match**: Required. String to search for.
//! - **include**: Optional. Boolean value indicating whether to return substrings that include
//!   or exclude match. If True (default), Filter returns subset including match. If False,
//!   Filter returns subset excluding match.
//! - **compare**: Optional. Numeric value indicating the kind of string comparison to use.
//!   * 0 = vbBinaryCompare (case-sensitive, default)
//!   * 1 = vbTextCompare (case-insensitive)
//!   * 2 = vbDatabaseCompare (Microsoft Access only)
//!
//! ## Return Value
//!
//! Returns a `Variant` containing a zero-based array of strings. If no matches are found,
//! Filter returns an empty array. If sourcearray is Null or not a one-dimensional array,
//! an error occurs.
//!
//! ## Remarks
//!
//! The `Filter` function searches a string array for elements containing a specified substring
//! and returns a new array with matching (or non-matching) elements. This is useful for
//! filtering lists, implementing search functionality, and processing string collections.
//!
//! ## Important Characteristics
//!
//! - Returns zero-based array regardless of input array bounds
//! - Match is substring search (not whole string match)
//! - Empty string match returns all elements (when include=True)
//! - Returns empty array if no matches found
//! - Case sensitivity controlled by compare parameter
//! - Original array is not modified
//! - Works only with one-dimensional string arrays
//! - Error 13 (Type Mismatch) if sourcearray is not an array
//! - Error 5 (Invalid procedure call) if sourcearray is multi-dimensional
//! - Error 94 (Invalid use of Null) if sourcearray is Null
//! - Returned array starts at index 0
//! - Can be used to implement NOT logic (include=False)
//!
//! ### Common Errors
//!
//! - **Error 13** (Type Mismatch): sourcearray is not an array or not a string array
//! - **Error 5** (Invalid procedure call): sourcearray is multi-dimensional
//! - **Error 94** (Invalid use of Null): sourcearray is Null
//!
//! ## Performance Considerations
//!
//! - Filter is efficient for small to medium arrays (< 10,000 elements)
//! - For very large arrays, consider Dictionary-based approaches
//! - Case-insensitive search is slightly slower than case-sensitive
//! - Filtering already-filtered results is faster than re-filtering original array
//! - Consider caching results for repeated searches
//! - Empty string match returns entire array
//!
//! ## Typical Uses
//!
//! - Filter lists based on user input
//! - Implement search functionality
//! - Remove unwanted items from arrays
//! - Find items matching a pattern
//! - Create subsets of data
//! - Filter file lists
//! - Process search results
//! - Implement autocomplete features
//!
//! ## Limitations
//!
//! - Works only with one-dimensional arrays
//! - Only supports string arrays
//! - Returns zero-based array (even if source is 1-based)
//! - Substring match only (no regex or wildcards)
//! - Cannot filter on multiple criteria in single call
//! - No built-in support for custom comparison functions
//! - Case-insensitive limited to vbTextCompare behavior
//!
//! ## Related Functions
//!
//! - `Array`: Creates a `Variant` array
//! - `Split`: Splits a string into an array
//! - `Join`: Joins array elements into a string
//! - `InStr`: Finds substring position
//! - `LBound`/`UBound`: Gets array bounds
//! - `IsArray`: Checks if variable is an array
//!
//! ## Examples
//!
//! ### Basic Usage
//!
//! ```vb6
//! Dim fruits() As String
//! Dim filtered() As String
//!
//! fruits = Array("Apple", "Banana", "Cherry", "Date", "Elderberry")
//!
//! ' Find fruits containing "e" (case-sensitive)
//! filtered = Filter(fruits, "e")
//! ' Returns: "Apple", "Cherry", "Date", "Elderberry"
//!
//! ' Find fruits NOT containing "e"
//! filtered = Filter(fruits, "e", False)
//! ' Returns: "Banana"
//!
//! ' Find fruits containing "a" (case-insensitive)
//! filtered = Filter(fruits, "a", True, vbTextCompare)
//! ' Returns: "Apple", "Banana", "Date"
//! ```
//!
//! ### Case-Sensitive vs Case-Insensitive
//!
//! ```vb6
//! Dim names() As String
//! names = Array("John", "jane", "JAMES", "Julia", "jack")
//!
//! ' Case-sensitive search (default)
//! Dim result1() As String
//! result1 = Filter(names, "J")
//! ' Returns: "John", "JAMES", "Julia"
//!
//! ' Case-insensitive search
//! Dim result2() As String
//! result2 = Filter(names, "J", True, vbTextCompare)
//! ' Returns: "John", "jane", "JAMES", "Julia", "jack"
//! ```
//!
//! ### Exclude Matches
//!
//! ```vb6
//! Dim files() As String
//! files = Array("data.txt", "backup.bak", "report.txt", "temp.bak", "notes.txt")
//!
//! ' Get only non-backup files (exclude .bak)
//! Dim textFiles() As String
//! textFiles = Filter(files, ".bak", False)
//! ' Returns: "data.txt", "report.txt", "notes.txt"
//! ```
//!
//! ## Common Patterns
//!
//! ### Filter List Based on User Input
//!
//! ```vb6
//! Function SearchList(items() As String, searchTerm As String) As String()
//!     On Error GoTo ErrorHandler
//!     
//!     If Trim(searchTerm) = "" Then
//!         ' Return all items if search is empty
//!         SearchList = items
//!     Else
//!         ' Return filtered items (case-insensitive)
//!         SearchList = Filter(items, searchTerm, True, vbTextCompare)
//!     End If
//!     
//!     Exit Function
//!     
//! ErrorHandler:
//!     ' Return empty array on error
//!     Dim emptyArray() As String
//!     ReDim emptyArray(0 To -1)
//!     SearchList = emptyArray
//! End Function
//! ```
//!
//! ### Count Matching Items
//!
//! ```vb6
//! Function CountMatches(items() As String, searchTerm As String) As Long
//!     On Error GoTo ErrorHandler
//!     
//!     Dim matches() As String
//!     matches = Filter(items, searchTerm, True, vbTextCompare)
//!     
//!     ' Check if array is empty
//!     If UBound(matches) >= 0 Then
//!         CountMatches = UBound(matches) + 1
//!     Else
//!         CountMatches = 0
//!     End If
//!     
//!     Exit Function
//!     
//! ErrorHandler:
//!     CountMatches = 0
//! End Function
//! ```
//!
//! ### Filter File List by Extension
//!
//! ```vb6
//! Function GetFilesByExtension(files() As String, extension As String) As String()
//!     ' Ensure extension starts with dot
//!     If Left(extension, 1) <> "." Then
//!         extension = "." & extension
//!     End If
//!     
//!     ' Filter for files with this extension
//!     GetFilesByExtension = Filter(files, extension, True, vbTextCompare)
//! End Function
//!
//! ' Usage
//! Dim allFiles() As String
//! Dim txtFiles() As String
//! allFiles = Array("doc1.txt", "image.jpg", "data.txt", "photo.png")
//! txtFiles = GetFilesByExtension(allFiles, ".txt")
//! ```
//!
//! ### Multiple Filter Criteria
//!
//! ```vb6
//! Function FilterMultiple(items() As String, filters() As String) As String()
//!     Dim result() As String
//!     Dim temp() As String
//!     Dim i As Long
//!     
//!     result = items
//!     
//!     ' Apply each filter sequentially
//!     For i = LBound(filters) To UBound(filters)
//!         temp = Filter(result, filters(i), True, vbTextCompare)
//!         result = temp
//!         
//!         ' Exit early if no matches
//!         If UBound(result) < 0 Then Exit For
//!     Next i
//!     
//!     FilterMultiple = result
//! End Function
//!
//! ' Usage: Find items containing both "test" and "data"
//! Dim criteria() As String
//! criteria = Array("test", "data")
//! filtered = FilterMultiple(sourceArray, criteria)
//! ```
//!
//! ### Populate `ListBox` with Filtered Results
//!
//! ```vb6
//! Sub UpdateFilteredList(lstBox As ListBox, items() As String, searchText As String)
//!     Dim filtered() As String
//!     Dim i As Long
//!     
//!     lstBox.Clear
//!     
//!     On Error GoTo ErrorHandler
//!     
//!     If Trim(searchText) = "" Then
//!         ' Show all items
//!         For i = LBound(items) To UBound(items)
//!             lstBox.AddItem items(i)
//!         Next i
//!     Else
//!         ' Show filtered items
//!         filtered = Filter(items, searchText, True, vbTextCompare)
//!         
//!         If UBound(filtered) >= 0 Then
//!             For i = 0 To UBound(filtered)
//!                 lstBox.AddItem filtered(i)
//!             Next i
//!         End If
//!     End If
//!     
//!     Exit Sub
//!     
//! ErrorHandler:
//!     ' Handle errors silently or show message
//! End Sub
//! ```
//!
//! ### Remove Duplicates with Filter
//!
//! ```vb6
//! Function RemoveDuplicates(items() As String) As String()
//!     Dim result() As String
//!     Dim dict As Object
//!     Dim i As Long
//!     Dim count As Long
//!     
//!     Set dict = CreateObject("Scripting.Dictionary")
//!     dict.CompareMode = vbTextCompare
//!     
//!     ' Add unique items to dictionary
//!     For i = LBound(items) To UBound(items)
//!         If Not dict.Exists(items(i)) Then
//!             dict.Add items(i), Nothing
//!         End If
//!     Next i
//!     
//!     ' Convert to array
//!     ReDim result(0 To dict.Count - 1)
//!     count = 0
//!     For i = 0 To dict.Count - 1
//!         result(count) = dict.Keys()(i)
//!         count = count + 1
//!     Next i
//!     
//!     RemoveDuplicates = result
//! End Function
//! ```
//!
//! ### Filter with Wildcard Simulation
//!
//! ```vb6
//! Function FilterWildcard(items() As String, pattern As String) As Collection
//!     ' Simple wildcard: * at start, end, or both
//!     Dim results As New Collection
//!     Dim filtered() As String
//!     Dim searchTerm As String
//!     Dim i As Long
//!     Dim item As String
//!     
//!     If Left(pattern, 1) = "*" And Right(pattern, 1) = "*" Then
//!         ' Contains search
//!         searchTerm = Mid(pattern, 2, Len(pattern) - 2)
//!         filtered = Filter(items, searchTerm, True, vbTextCompare)
//!         
//!         For i = 0 To UBound(filtered)
//!             results.Add filtered(i)
//!         Next i
//!         
//!     ElseIf Left(pattern, 1) = "*" Then
//!         ' Ends with search
//!         searchTerm = Mid(pattern, 2)
//!         For i = LBound(items) To UBound(items)
//!             If Right(LCase(items(i)), Len(searchTerm)) = LCase(searchTerm) Then
//!                 results.Add items(i)
//!             End If
//!         Next i
//!         
//!     ElseIf Right(pattern, 1) = "*" Then
//!         ' Starts with search
//!         searchTerm = Left(pattern, Len(pattern) - 1)
//!         For i = LBound(items) To UBound(items)
//!             If Left(LCase(items(i)), Len(searchTerm)) = LCase(searchTerm) Then
//!                 results.Add items(i)
//!             End If
//!         Next i
//!         
//!     Else
//!         ' Exact match
//!         For i = LBound(items) To UBound(items)
//!             If LCase(items(i)) = LCase(pattern) Then
//!                 results.Add items(i)
//!             End If
//!         Next i
//!     End If
//!     
//!     Set FilterWildcard = results
//! End Function
//! ```
//!
//! ### Autocomplete Implementation
//!
//! ```vb6
//! Sub TextBox_Change()
//!     Dim allItems() As String
//!     Dim matches() As String
//!     Dim i As Long
//!     
//!     ' Get all possible values (from database, array, etc.)
//!     allItems = GetAllItemNames()
//!     
//!     If Len(Me.txtSearch.Text) > 0 Then
//!         ' Filter items that start with typed text
//!         matches = Filter(allItems, Me.txtSearch.Text, True, vbTextCompare)
//!         
//!         ' Display suggestions
//!         Me.lstSuggestions.Clear
//!         
//!         If UBound(matches) >= 0 Then
//!             For i = 0 To UBound(matches)
//!                 Me.lstSuggestions.AddItem matches(i)
//!             Next i
//!             Me.lstSuggestions.Visible = True
//!         Else
//!             Me.lstSuggestions.Visible = False
//!         End If
//!     Else
//!         Me.lstSuggestions.Visible = False
//!     End If
//! End Sub
//! ```
//!
//! ### Filter Log Entries
//!
//! ```vb6
//! Function FilterLogsByLevel(logEntries() As String, level As String) As String()
//!     ' Assume log format: "[LEVEL] Message"
//!     Dim levelTag As String
//!     levelTag = "[" & UCase(level) & "]"
//!     
//!     FilterLogsByLevel = Filter(logEntries, levelTag, True, vbTextCompare)
//! End Function
//!
//! ' Usage
//! Dim logs() As String
//! Dim errors() As String
//! logs = Array("[INFO] Started", "[ERROR] Failed", "[INFO] Complete", "[ERROR] Timeout")
//! errors = FilterLogsByLevel(logs, "ERROR")
//! ' Returns: "[ERROR] Failed", "[ERROR] Timeout"
//! ```
//!
//! ### Check If Array Contains Value
//!
//! ```vb6
//! Function ArrayContains(items() As String, value As String, _
//!                        Optional caseSensitive As Boolean = False) As Boolean
//!     On Error GoTo ErrorHandler
//!     
//!     Dim matches() As String
//!     Dim compareMode As VbCompareMethod
//!     
//!     If caseSensitive Then
//!         compareMode = vbBinaryCompare
//!     Else
//!         compareMode = vbTextCompare
//!     End If
//!     
//!     matches = Filter(items, value, True, compareMode)
//!     
//!     ' Check if any exact matches
//!     Dim i As Long
//!     For i = 0 To UBound(matches)
//!         If StrComp(matches(i), value, compareMode) = 0 Then
//!             ArrayContains = True
//!             Exit Function
//!         End If
//!     Next i
//!     
//!     ArrayContains = False
//!     Exit Function
//!     
//! ErrorHandler:
//!     ArrayContains = False
//! End Function
//! ```
//!
//! ### Combine Include and Exclude Filters
//!
//! ```vb6
//! Function FilterIncludeExclude(items() As String, includeText As String, _
//!                               excludeText As String) As String()
//!     Dim temp() As String
//!     
//!     ' First include items containing includeText
//!     If includeText <> "" Then
//!         temp = Filter(items, includeText, True, vbTextCompare)
//!     Else
//!         temp = items
//!     End If
//!     
//!     ' Then exclude items containing excludeText
//!     If excludeText <> "" And UBound(temp) >= 0 Then
//!         temp = Filter(temp, excludeText, False, vbTextCompare)
//!     End If
//!     
//!     FilterIncludeExclude = temp
//! End Function
//!
//! ' Usage: Get .txt files but not backup files
//! filtered = FilterIncludeExclude(files, ".txt", "backup")
//! ```
//!
//! ## Advanced Usage
//!
//! ### Dynamic Search with Multiple Columns
//!
//! ```vb6
//! Type RecordData
//!     ID As String
//!     Name As String
//!     Email As String
//!     Department As String
//! End Type
//!
//! Function SearchRecords(records() As RecordData, searchTerm As String) As Long()
//!     ' Search across multiple fields and return matching indices
//!     Dim names() As String
//!     Dim emails() As String
//!     Dim departments() As String
//!     Dim matchedNames() As String
//!     Dim matchedEmails() As String
//!     Dim matchedDepts() As String
//!     Dim results() As Long
//!     Dim i As Long
//!     Dim count As Long
//!     Dim dict As Object
//!     
//!     Set dict = CreateObject("Scripting.Dictionary")
//!     
//!     ' Build arrays for each searchable field
//!     ReDim names(LBound(records) To UBound(records))
//!     ReDim emails(LBound(records) To UBound(records))
//!     ReDim departments(LBound(records) To UBound(records))
//!     
//!     For i = LBound(records) To UBound(records)
//!         names(i) = records(i).Name
//!         emails(i) = records(i).Email
//!         departments(i) = records(i).Department
//!     Next i
//!     
//!     ' Filter each field
//!     On Error Resume Next
//!     matchedNames = Filter(names, searchTerm, True, vbTextCompare)
//!     matchedEmails = Filter(emails, searchTerm, True, vbTextCompare)
//!     matchedDepts = Filter(departments, searchTerm, True, vbTextCompare)
//!     On Error GoTo 0
//!     
//!     ' Collect unique matching indices
//!     For i = LBound(records) To UBound(records)
//!         If InStr(1, records(i).Name, searchTerm, vbTextCompare) > 0 Or _
//!            InStr(1, records(i).Email, searchTerm, vbTextCompare) > 0 Or _
//!            InStr(1, records(i).Department, searchTerm, vbTextCompare) > 0 Then
//!             
//!             If Not dict.Exists(i) Then
//!                 dict.Add i, Nothing
//!             End If
//!         End If
//!     Next i
//!     
//!     ' Convert to array
//!     If dict.Count > 0 Then
//!         ReDim results(0 To dict.Count - 1)
//!         For i = 0 To dict.Count - 1
//!             results(i) = dict.Keys()(i)
//!         Next i
//!     Else
//!         ReDim results(0 To -1)
//!     End If
//!     
//!     SearchRecords = results
//! End Function
//! ```
//!
//! ### Incremental Filter (Type-Ahead)
//!
//! ```vb6
//! Private lastSearch As String
//! Private cachedResults() As String
//!
//! Sub IncrementalSearch(items() As String, currentSearch As String)
//!     Dim filtered() As String
//!     
//!     ' If new search starts with last search, filter cached results
//!     If Len(currentSearch) > Len(lastSearch) And _
//!        Left(currentSearch, Len(lastSearch)) = lastSearch And _
//!        UBound(cachedResults) >= 0 Then
//!         
//!         ' Filter from cached results (faster)
//!         filtered = Filter(cachedResults, currentSearch, True, vbTextCompare)
//!     Else
//!         ' Filter from full list
//!         filtered = Filter(items, currentSearch, True, vbTextCompare)
//!     End If
//!     
//!     ' Update cache
//!     cachedResults = filtered
//!     lastSearch = currentSearch
//!     
//!     ' Display results
//!     DisplayResults filtered
//! End Sub
//! ```
//!
//! ### Category-Based Filtering
//!
//! ```vb6
//! Type Product
//!     Name As String
//!     Category As String
//!     Price As Double
//!     Description As String
//! End Type
//!
//! Function FilterProductsByCategory(products() As Product, _
//!                                   category As String) As Product()
//!     Dim categories() As String
//!     Dim filtered() As String
//!     Dim results() As Product
//!     Dim i As Long
//!     Dim count As Long
//!     
//!     ' Build category array
//!     ReDim categories(LBound(products) To UBound(products))
//!     For i = LBound(products) To UBound(products)
//!         categories(i) = products(i).Category
//!     Next i
//!     
//!     ' Get matching categories
//!     filtered = Filter(categories, category, True, vbTextCompare)
//!     
//!     ' Build result array
//!     ReDim results(0 To UBound(filtered))
//!     count = 0
//!     
//!     For i = LBound(products) To UBound(products)
//!         If InStr(1, products(i).Category, category, vbTextCompare) > 0 Then
//!             results(count) = products(i)
//!             count = count + 1
//!         End If
//!     Next i
//!     
//!     If count > 0 Then
//!         ReDim Preserve results(0 To count - 1)
//!     Else
//!         ReDim results(0 To -1)
//!     End If
//!     
//!     FilterProductsByCategory = results
//! End Function
//! ```
//!
//! ### Filter with Performance Tracking
//!
//! ```vb6
//! Function FilterWithStats(items() As String, searchTerm As String, _
//!                          ByRef matchCount As Long, _
//!                          ByRef elapsedMs As Double) As String()
//!     Dim startTime As Double
//!     Dim results() As String
//!     
//!     startTime = Timer
//!     
//!     On Error GoTo ErrorHandler
//!     results = Filter(items, searchTerm, True, vbTextCompare)
//!     
//!     If UBound(results) >= 0 Then
//!         matchCount = UBound(results) + 1
//!     Else
//!         matchCount = 0
//!     End If
//!     
//!     elapsedMs = (Timer - startTime) * 1000
//!     
//!     FilterWithStats = results
//!     Exit Function
//!     
//! ErrorHandler:
//!     matchCount = 0
//!     elapsedMs = 0
//!     ReDim results(0 To -1)
//!     FilterWithStats = results
//! End Function
//! ```
//!
//! ### Smart Case-Sensitive Filter
//!
//! ```vb6
//! Function SmartFilter(items() As String, searchTerm As String) As String()
//!     Dim compareMode As VbCompareMethod
//!     
//!     ' If search term has uppercase letters, use case-sensitive
//!     ' Otherwise use case-insensitive
//!     If searchTerm <> LCase(searchTerm) Then
//!         compareMode = vbBinaryCompare
//!     Else
//!         compareMode = vbTextCompare
//!     End If
//!     
//!     SmartFilter = Filter(items, searchTerm, True, compareMode)
//! End Function
//! ```
//!
//! ## Error Handling
//!
//! ```vb6
//! Function SafeFilter(items As Variant, searchTerm As String) As Variant
//!     On Error GoTo ErrorHandler
//!     
//!     Dim emptyArray() As String
//!     
//!     ' Check if items is an array
//!     If Not IsArray(items) Then
//!         ReDim emptyArray(0 To -1)
//!         SafeFilter = emptyArray
//!         Exit Function
//!     End If
//!     
//!     ' Check if items is Null
//!     If IsNull(items) Then
//!         ReDim emptyArray(0 To -1)
//!         SafeFilter = emptyArray
//!         Exit Function
//!     End If
//!     
//!     ' Perform filter
//!     SafeFilter = Filter(items, searchTerm, True, vbTextCompare)
//!     Exit Function
//!     
//! ErrorHandler:
//!     Select Case Err.Number
//!         Case 13  ' Type mismatch
//!             Debug.Print "Filter error: sourcearray is not a string array"
//!         Case 5   ' Invalid procedure call
//!             Debug.Print "Filter error: sourcearray is multi-dimensional"
//!         Case 94  ' Invalid use of Null
//!             Debug.Print "Filter error: sourcearray is Null"
//!         Case Else
//!             Debug.Print "Filter error " & Err.Number & ": " & Err.Description
//!     End Select
//!     
//!     ReDim emptyArray(0 To -1)
//!     SafeFilter = emptyArray
//! End Function
//! ```
//!
//! ## Best Practices
//!
//! ### Always Check Result Array
//!
//! ```vb6
//! Dim results() As String
//! results = Filter(items, searchTerm)
//!
//! If UBound(results) >= 0 Then
//!     ' Process results
//!     For i = 0 To UBound(results)
//!         Debug.Print results(i)
//!     Next i
//! Else
//!     Debug.Print "No matches found"
//! End If
//! ```
//!
//! ### Use Error Handling
//!
//! ```vb6
//! On Error Resume Next
//! filtered = Filter(sourceArray, searchText, True, vbTextCompare)
//! If Err.Number <> 0 Then
//!     ' Handle error
//!     ReDim filtered(0 To -1)
//! End If
//! On Error GoTo 0
//! ```
//!
//! ### Default to Case-Insensitive for User Input
//!
//! ```vb6
//! ' Good - User-friendly search
//! results = Filter(items, userInput, True, vbTextCompare)
//!
//! ' Less friendly - Exact case required
//! results = Filter(items, userInput)
//! ```
//!
//! ## Comparison with Other Approaches
//!
//! ### Filter vs Manual Loop
//!
//! ```vb6
//! ' Using Filter (concise)
//! matches = Filter(items, searchTerm, True, vbTextCompare)
//!
//! ' Manual loop (more control)
//! ReDim matches(0 To UBound(items))
//! count = 0
//! For i = LBound(items) To UBound(items)
//!     If InStr(1, items(i), searchTerm, vbTextCompare) > 0 Then
//!         matches(count) = items(i)
//!         count = count + 1
//!     End If
//! Next i
//! If count > 0 Then
//!     ReDim Preserve matches(0 To count - 1)
//! End If
//! ```
//!
//! ### Filter vs Collection/Dictionary
//!
//! ```vb6
//! ' Filter - Returns array
//! Dim arr() As String
//! arr = Filter(items, searchTerm)
//!
//! ' Collection - More flexible but slower
//! Dim coll As New Collection
//! For i = LBound(items) To UBound(items)
//!     If InStr(1, items(i), searchTerm, vbTextCompare) > 0 Then
//!         coll.Add items(i)
//!     End If
//! Next i
//! ```

use crate::array::ArrayValue;
use crate::error::{err_number, VBError, VBResult};
use crate::types::VBType;
use crate::value::{VBBoolean, VBLong, VBString, VBVariant};

/// Implementation of the `Filter` function.
///
/// Searches a one-dimensional string array for elements containing (or not
/// containing) a specified substring and returns a zero-based array of the
/// matching elements.
///
/// VB6 behavior:
/// - Returns a zero-based array regardless of the input array's bounds
/// - Performs substring matching (not whole-string match)
/// - `include` defaults to `True` (return matches); `False` excludes matches
/// - `compare` accepts `vbUseCompareOption` (-1), `vbBinaryCompare` (0),
///   `vbTextCompare` (1), and `vbDatabaseCompare` (2); without a module-level
///   `Option Compare` or database setting, -1 and 2 behave as binary compare,
///   and any other value raises error 5 (invalid procedure call)
/// - Empty `match` string with `include=True` returns all elements
/// - Returns an empty array when no matches are found, or when `sourcearray`
///   is a zero-length or still undimensioned array
/// - Matching is case-sensitive unless `vbTextCompare` (1) is given, and the
///   original casing of matched elements is preserved
/// - Raises error 94 if `sourcearray` is Null, or if it contains a `Null`
///   element
/// - Raises error 13 if `sourcearray` is not an array, or if it contains a
///   non-string element
/// - Raises error 5 if `sourcearray` is multi-dimensional
pub fn filter(
    sourcearray: &VBVariant,
    match_string: &VBString,
    include: Option<&VBBoolean>,
    compare: Option<&VBLong>,
) -> VBResult<VBVariant> {
    // Validate sourcearray is not Null
    if sourcearray.is_null() {
        return Err(VBError::with_description(
            err_number::INVALID_USE_OF_NULL,
            "Invalid use of Null",
        ));
    }

    // Validate sourcearray is an array
    let VBVariant::Array(arr) = sourcearray else {
        return Err(VBError::type_mismatch());
    };

    // A zero-length (or still undimensioned) array returns an empty array
    if !arr.is_initialized() || arr.is_empty() {
        return Ok(VBVariant::Array(ArrayValue::from_vec_with_bounds(
            VBType::String,
            Vec::new(),
            0,
        )));
    }

    // Check for multi-dimensional arrays
    if arr.rank() != 1 {
        return Err(VBError::with_description(
            err_number::INVALID_PROCEDURE_CALL,
            "Multi-dimensional array",
        ));
    }

    let include = include.is_none_or(|b| b.as_bool());
    let text_compare = match compare.map(|c| c.as_i32()) {
        None => false,
        Some(mode) if (-1..=2).contains(&mode) => mode == 1,
        Some(_) => return Err(VBError::invalid_procedure_call()),
    };

    // Collect matching elements in source order
    let lower = arr.lower_bound(0).unwrap();
    let upper = arr.upper_bound(0).unwrap();
    let mut matches: Vec<VBVariant> = Vec::new();

    for i in lower..=upper {
        let element = arr.get(&[i]).unwrap();
        let element_str = match element {
            VBVariant::Null => return Err(VBError::invalid_use_of_null()),
            VBVariant::String(s) => s.as_str(),
            _ => return Err(VBError::type_mismatch()),
        };

        let contains = if text_compare {
            element_str
                .to_lowercase()
                .contains(&match_string.as_str().to_lowercase())
        } else {
            element_str.contains(match_string.as_str())
        };

        if (include && contains) || (!include && !contains) {
            matches.push(VBVariant::from_string(element_str));
        }
    }

    // Return zero-based array
    Ok(VBVariant::Array(ArrayValue::from_vec_with_bounds(
        VBType::String,
        matches,
        0,
    )))
}

#[cfg(test)]
mod tests {
    use super::filter;
    use crate::array::{ArrayDimension, ArrayValue};
    use crate::error::err_number;
    use crate::types::VBType;
    use crate::value::{VBBoolean, VBLong, VBString, VBVariant};

    fn make_string_array(strings: &[&str]) -> VBVariant {
        let data: Vec<VBVariant> = strings.iter().map(|s| VBVariant::from_string(*s)).collect();
        VBVariant::Array(ArrayValue::from_vec_with_bounds(VBType::String, data, 0))
    }

    fn extract_strings(variant: &VBVariant) -> Vec<String> {
        let arr = variant.as_array().unwrap();
        (0..arr.len())
            .map(|i| {
                arr.get(&[i as i32])
                    .unwrap()
                    .as_str()
                    .unwrap_or("")
                    .to_string()
            })
            .collect()
    }

    #[test]
    fn basic_filter_includes_matches() {
        let source = make_string_array(&["Apple", "Banana", "Cherry", "Date", "Elderberry"]);
        let result = filter(&source, &VBString::from("e"), None, None).unwrap();
        let matches = extract_strings(&result);

        assert_eq!(matches, vec!["Apple", "Cherry", "Date", "Elderberry"]);
    }

    #[test]
    fn filter_excludes_matches() {
        let source = make_string_array(&["Apple", "Banana", "Cherry", "Date", "Elderberry"]);
        let result = filter(
            &source,
            &VBString::from("e"),
            Some(&VBBoolean::from(false)),
            None,
        )
        .unwrap();
        let matches = extract_strings(&result);

        assert_eq!(matches, vec!["Banana"]);
    }

    #[test]
    fn text_compare_is_case_insensitive() {
        let source = make_string_array(&["Apple", "Banana", "Cherry"]);
        let result = filter(&source, &VBString::from("a"), None, Some(&VBLong::from(1))).unwrap();
        let matches = extract_strings(&result);

        assert_eq!(matches, vec!["Apple", "Banana"]);
    }

    #[test]
    fn binary_compare_is_case_sensitive() {
        let source = make_string_array(&["Apple", "apple", "BANANA"]);
        let result = filter(&source, &VBString::from("a"), None, Some(&VBLong::from(0))).unwrap();
        let matches = extract_strings(&result);

        assert_eq!(matches, vec!["apple"]);
    }

    #[test]
    fn empty_match_includes_all() {
        let source = make_string_array(&["a", "b", "c"]);
        let result = filter(&source, &VBString::from(""), None, None).unwrap();
        let matches = extract_strings(&result);

        assert_eq!(matches, vec!["a", "b", "c"]);
    }

    #[test]
    fn empty_match_excludes_none() {
        let source = make_string_array(&["a", "b", "c"]);
        let result = filter(
            &source,
            &VBString::from(""),
            Some(&VBBoolean::from(false)),
            None,
        )
        .unwrap();
        let matches = extract_strings(&result);

        // Empty string is contained in every string, so excluding gives empty result
        assert_eq!(matches, Vec::<String>::new());
    }

    #[test]
    fn no_matches_returns_empty_array() {
        let source = make_string_array(&["Apple", "Banana", "Cherry"]);
        let result = filter(&source, &VBString::from("xyz"), None, None).unwrap();
        let matches = extract_strings(&result);

        assert_eq!(matches, Vec::<String>::new());
    }

    #[test]
    fn returns_zero_based_array() {
        let source = make_string_array(&["a", "b", "c"]);
        let result = filter(&source, &VBString::from("a"), None, None).unwrap();
        let arr = result.as_array().unwrap();

        assert_eq!(arr.lower_bound(0).unwrap(), 0);
    }

    #[test]
    fn null_source_is_error_94() {
        let err = filter(&VBVariant::Null, &VBString::from("test"), None, None).unwrap_err();
        assert_eq!(err.number, err_number::INVALID_USE_OF_NULL);
    }

    #[test]
    fn non_array_is_error_13() {
        let err = filter(
            &VBVariant::from_string("not an array"),
            &VBString::from("test"),
            None,
            None,
        )
        .unwrap_err();
        assert_eq!(err.number, err_number::TYPE_MISMATCH);
    }

    #[test]
    fn preserves_original_strings() {
        let source = make_string_array(&["Hello World", "HELLO WORLD", "hello world"]);
        let result = filter(
            &source,
            &VBString::from("world"),
            None,
            Some(&VBLong::from(1)),
        )
        .unwrap();
        let matches = extract_strings(&result);

        // Text compare finds all three, original casing preserved
        assert_eq!(matches, vec!["Hello World", "HELLO WORLD", "hello world"]);
    }

    #[test]
    fn handles_one_based_arrays() {
        let data: Vec<VBVariant> = vec![
            VBVariant::from_string("Apple"),
            VBVariant::from_string("Banana"),
            VBVariant::from_string("Cherry"),
        ];
        let source = VBVariant::Array(ArrayValue::from_vec(VBType::String, data));
        let result = filter(&source, &VBString::from("e"), None, None).unwrap();
        assert_eq!(extract_strings(&result), vec!["Apple", "Cherry"]);
    }

    #[test]
    fn handles_arbitrary_lower_bound() {
        let data: Vec<VBVariant> = vec![
            VBVariant::from_string("a"),
            VBVariant::from_string("bb"),
            VBVariant::from_string("c"),
        ];
        let source = VBVariant::Array(ArrayValue::from_vec_with_bounds(VBType::String, data, -2));
        let result = filter(&source, &VBString::from("b"), None, None).unwrap();
        assert_eq!(extract_strings(&result), vec!["bb"]);
        // Result is zero-based even though the source was not
        assert_eq!(result.as_array().unwrap().lower_bound(0).unwrap(), 0);
    }

    #[test]
    fn non_string_element_is_error_13() {
        let data: Vec<VBVariant> = vec![
            VBVariant::from_string("Apple"),
            VBVariant::from_integer(42),
            VBVariant::from_string("Cherry"),
        ];
        let source = VBVariant::Array(ArrayValue::from_vec_with_bounds(VBType::Variant, data, 0));
        let err = filter(&source, &VBString::from("e"), None, None).unwrap_err();
        assert_eq!(err.number, err_number::TYPE_MISMATCH);
    }

    #[test]
    fn null_element_is_error_94() {
        let data: Vec<VBVariant> = vec![
            VBVariant::from_string("Apple"),
            VBVariant::Null,
            VBVariant::from_string("Cherry"),
        ];
        let source = VBVariant::Array(ArrayValue::from_vec_with_bounds(VBType::Variant, data, 0));
        let err = filter(&source, &VBString::from("e"), None, None).unwrap_err();
        assert_eq!(err.number, err_number::INVALID_USE_OF_NULL);
    }

    #[test]
    fn invalid_compare_is_error_5() {
        let source = make_string_array(&["Apple", "Banana"]);
        for compare in [3, 5, -2, 100] {
            let err = filter(
                &source,
                &VBString::from("a"),
                None,
                Some(&VBLong::from(compare)),
            )
            .unwrap_err();
            assert_eq!(
                err.number,
                err_number::INVALID_PROCEDURE_CALL,
                "compare = {compare}"
            );
        }
    }

    #[test]
    fn use_option_compare_defaults_to_binary() {
        let source = make_string_array(&["Apple", "apple"]);
        let result = filter(&source, &VBString::from("a"), None, Some(&VBLong::from(-1))).unwrap();
        assert_eq!(extract_strings(&result), vec!["apple"]);
    }

    #[test]
    fn database_compare_defaults_to_binary() {
        let source = make_string_array(&["Apple", "apple"]);
        let result = filter(&source, &VBString::from("a"), None, Some(&VBLong::from(2))).unwrap();
        assert_eq!(extract_strings(&result), vec!["apple"]);
    }

    #[test]
    fn explicit_binary_compare_is_case_sensitive() {
        let source = make_string_array(&["Apple", "apple"]);
        let result = filter(&source, &VBString::from("a"), None, Some(&VBLong::from(0))).unwrap();
        assert_eq!(extract_strings(&result), vec!["apple"]);
    }

    #[test]
    fn undimensioned_array_returns_empty() {
        let source = VBVariant::Array(ArrayValue::new_dynamic(VBType::String));
        let result = filter(&source, &VBString::from("x"), None, None).unwrap();
        assert!(extract_strings(&result).is_empty());
    }

    #[test]
    fn zero_length_array_returns_empty() {
        let source = VBVariant::Array(ArrayValue::from_vec_with_bounds(
            VBType::String,
            Vec::new(),
            0,
        ));
        let result = filter(&source, &VBString::from("x"), None, None).unwrap();
        assert!(extract_strings(&result).is_empty());
    }

    #[test]
    fn multi_dimensional_array_is_error_5() {
        let source = VBVariant::Array(
            ArrayValue::new_fixed(
                VBType::String,
                &[ArrayDimension::new(1, 2), ArrayDimension::new(1, 2)],
            )
            .unwrap(),
        );
        let err = filter(&source, &VBString::from("x"), None, None).unwrap_err();
        assert_eq!(err.number, err_number::INVALID_PROCEDURE_CALL);
    }

    #[test]
    fn result_bounds_reflect_match_count() {
        let source = make_string_array(&["Apple", "Banana", "Cherry"]);
        let result = filter(&source, &VBString::from("e"), None, None).unwrap();
        let arr = result.as_array().unwrap();
        assert_eq!(arr.lower_bound(0).unwrap(), 0);
        assert_eq!(arr.upper_bound(0).unwrap(), 1);
        assert_eq!(arr.len(), 2);
    }

    #[test]
    fn substring_match_is_not_whole_word() {
        let source = make_string_array(&["banana", "band", "apple"]);
        let result = filter(&source, &VBString::from("ban"), None, None).unwrap();
        assert_eq!(extract_strings(&result), vec!["banana", "band"]);
    }

    #[test]
    fn exclude_preserves_order() {
        let source = make_string_array(&["a", "b", "c", "d"]);
        let result = filter(
            &source,
            &VBString::from("b"),
            Some(&VBBoolean::from(false)),
            None,
        )
        .unwrap();
        assert_eq!(extract_strings(&result), vec!["a", "c", "d"]);
    }
}