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
//! # `MonthName` Function
//!
//! Returns a String indicating the specified month.
//!
//! ## Syntax
//!
//! ```vb
//! MonthName(month, [abbreviate])
//! ```
//!
//! ## Parameters
//!
//! - **month** (Required) - Numeric designation of the month. For example, January is 1, February is 2, and so on.
//! - **abbreviate** (Optional) - Boolean value that indicates if the month name is to be abbreviated. If omitted, the default is False, which means the month name is not abbreviated.
//!
//! ## Return Value
//!
//! Returns a **String** representing the month name:
//! - If abbreviate is False or omitted: Full month name (e.g., "January", "February")
//! - If abbreviate is True: Abbreviated month name (e.g., "Jan", "Feb")
//!
//! ## Remarks
//!
//! The `MonthName` function returns the localized name of the month based on the system's regional settings.
//! It is commonly used for displaying month names in user interfaces, reports, and formatted output.
//!
//! ### Key Characteristics:
//! - Returns localized month names based on system regional settings
//! - Month parameter must be between 1 and 12
//! - Error 5 (Invalid procedure call) if month is less than 1 or greater than 12
//! - Abbreviate parameter is optional; defaults to False (full name)
//! - Abbreviated names are typically 3 characters but may vary by locale
//! - Much simpler than maintaining arrays of month names
//! - Can be combined with `Month()` function for date formatting
//! - Respects system locale for internationalization
//!
//! ### Common Use Cases:
//! - Display month names in user interfaces
//! - Format dates for reports and output
//! - Create drop-down lists of months
//! - Generate calendar displays
//! - Internationalized date formatting
//! - Chart and graph labels
//! - File naming with month names
//! - Data export with readable month names
//!
//! ## Typical Uses
//!
//! 1. **Display Month Names** - Convert month numbers to readable names
//! 2. **Report Headers** - Format report titles with month names
//! 3. **Calendar Controls** - Populate month selectors
//! 4. **Data Export** - Include readable month names in exports
//! 5. **User Interface** - Display current or selected month
//! 6. **Chart Labels** - Label chart axes with month names
//! 7. **File Naming** - Create month-based file names
//! 8. **Internationalization** - Automatic locale-based month names
//!
//! ## Basic Examples
//!
//! ```vb
//! ' Example 1: Get full month name
//! Dim monthName As String
//! monthName = MonthName(3)
//! ' Returns "March"
//! ```
//!
//! ```vb
//! ' Example 2: Get abbreviated month name
//! Dim shortMonth As String
//! shortMonth = MonthName(11, True)
//! ' Returns "Nov"
//! ```
//!
//! ```vb
//! ' Example 3: Display current month
//! Dim currentMonthName As String
//! currentMonthName = MonthName(Month(Date))
//! MsgBox "Current month is " & currentMonthName
//! ```
//!
//! ```vb
//! ' Example 4: Format date with month name
//! Dim formattedDate As String
//! Dim d As Date
//! d = #5/15/2025#
//! formattedDate = MonthName(Month(d)) & " " & Day(d) & ", " & Year(d)
//! ' Returns "May 15, 2025"
//! ```
//!
//! ## Common Patterns
//!
//! ```vb
//! ' Pattern 1: Safe month name with validation
//! Function SafeMonthName(monthNumber As Integer, _
//!                        Optional abbreviate As Boolean = False) As String
//!     If monthNumber < 1 Or monthNumber > 12 Then
//!         SafeMonthName = ""
//!     Else
//!         SafeMonthName = MonthName(monthNumber, abbreviate)
//!     End If
//! End Function
//! ```
//!
//! ```vb
//! ' Pattern 2: Populate month combo box
//! Sub PopulateMonthCombo(cbo As ComboBox, Optional abbreviate As Boolean = False)
//!     Dim i As Integer
//!     cbo.Clear
//!     For i = 1 To 12
//!         cbo.AddItem MonthName(i, abbreviate)
//!     Next i
//! End Sub
//! ```
//!
//! ```vb
//! ' Pattern 3: Get month name from date
//! Function GetMonthNameFromDate(dateValue As Date, _
//!                               Optional abbreviate As Boolean = False) As String
//!     GetMonthNameFromDate = MonthName(Month(dateValue), abbreviate)
//! End Function
//! ```
//!
//! ```vb
//! ' Pattern 4: Format date range with month names
//! Function FormatDateRange(startDate As Date, endDate As Date) As String
//!     Dim startMonth As String
//!     Dim endMonth As String
//!     
//!     startMonth = MonthName(Month(startDate), True)
//!     endMonth = MonthName(Month(endDate), True)
//!     
//!     FormatDateRange = startMonth & " " & Day(startDate) & " - " & _
//!                       endMonth & " " & Day(endDate) & ", " & Year(endDate)
//! End Function
//! ```
//!
//! ```vb
//! ' Pattern 5: Create month-based filename
//! Function GetMonthlyFileName(fileDate As Date, fileType As String) As String
//!     Dim monthAbbrev As String
//!     monthAbbrev = MonthName(Month(fileDate), True)
//!     GetMonthlyFileName = fileType & "_" & Year(fileDate) & "_" & monthAbbrev & ".dat"
//! End Function
//! ```
//!
//! ```vb
//! ' Pattern 6: Build month selection array
//! Function GetMonthArray(fullNames As Boolean) As String()
//!     Dim months() As String
//!     Dim i As Integer
//!     
//!     ReDim months(1 To 12)
//!     For i = 1 To 12
//!         months(i) = MonthName(i, Not fullNames)
//!     Next i
//!     
//!     GetMonthArray = months
//! End Function
//! ```
//!
//! ```vb
//! ' Pattern 7: Format month/year string
//! Function FormatMonthYear(dateValue As Date, abbreviate As Boolean) As String
//!     FormatMonthYear = MonthName(Month(dateValue), abbreviate) & " " & Year(dateValue)
//! End Function
//! ```
//!
//! ```vb
//! ' Pattern 8: Get fiscal month name
//! Function GetFiscalMonthName(fiscalMonth As Integer, abbreviate As Boolean) As String
//!     ' Fiscal month 1 might be October (calendar month 10)
//!     Dim calendarMonth As Integer
//!     Dim fiscalStartMonth As Integer
//!     
//!     fiscalStartMonth = 10 ' October
//!     calendarMonth = fiscalMonth + fiscalStartMonth - 1
//!     
//!     If calendarMonth > 12 Then
//!         calendarMonth = calendarMonth - 12
//!     End If
//!     
//!     GetFiscalMonthName = MonthName(calendarMonth, abbreviate)
//! End Function
//! ```
//!
//! ```vb
//! ' Pattern 9: Create report header
//! Function CreateMonthlyReportHeader(reportDate As Date) As String
//!     Dim header As String
//!     header = "Monthly Report - " & MonthName(Month(reportDate)) & " " & Year(reportDate)
//!     CreateMonthlyReportHeader = header
//! End Function
//! ```
//!
//! ```vb
//! ' Pattern 10: Compare month names
//! Function IsSameMonth(date1 As Date, date2 As Date) As Boolean
//!     IsSameMonth = (MonthName(Month(date1)) = MonthName(Month(date2))) And _
//!                   (Year(date1) = Year(date2))
//! End Function
//! ```
//!
//! ## Advanced Usage
//!
//! ### Example 1: Calendar Generator
//!
//! ```vb
//! ' Class: CalendarGenerator
//! ' Generates formatted calendar displays
//!
//! Option Explicit
//!
//! Private m_year As Integer
//! Private m_month As Integer
//! Private m_firstDayOfWeek As VbDayOfWeek
//!
//! Public Sub Initialize(calYear As Integer, calMonth As Integer)
//!     m_year = calYear
//!     m_month = calMonth
//!     m_firstDayOfWeek = vbSunday
//! End Sub
//!
//! Public Function GetMonthHeader(abbreviate As Boolean) As String
//!     GetMonthHeader = MonthName(m_month, abbreviate) & " " & m_year
//! End Function
//!
//! Public Function GenerateCalendar() As String
//!     Dim calendar As String
//!     Dim firstDay As Date
//!     Dim lastDay As Date
//!     Dim currentDay As Date
//!     Dim dayOfWeek As Integer
//!     Dim weekRow As String
//!     Dim dayCount As Integer
//!     
//!     ' Create header
//!     calendar = String(28, " ") & GetMonthHeader(False) & vbCrLf
//!     calendar = calendar & "Su  Mo  Tu  We  Th  Fr  Sa" & vbCrLf
//!     
//!     ' Get first and last day of month
//!     firstDay = DateSerial(m_year, m_month, 1)
//!     lastDay = DateSerial(m_year, m_month + 1, 0)
//!     
//!     ' Start with padding for first week
//!     dayOfWeek = Weekday(firstDay, m_firstDayOfWeek)
//!     weekRow = String((dayOfWeek - 1) * 4, " ")
//!     
//!     ' Fill in days
//!     currentDay = firstDay
//!     Do While currentDay <= lastDay
//!         weekRow = weekRow & Format(Day(currentDay), "00") & "  "
//!         dayOfWeek = dayOfWeek + 1
//!         
//!         If dayOfWeek > 7 Then
//!             calendar = calendar & weekRow & vbCrLf
//!             weekRow = ""
//!             dayOfWeek = 1
//!         End If
//!         
//!         currentDay = DateAdd("d", 1, currentDay)
//!     Loop
//!     
//!     If Len(weekRow) > 0 Then
//!         calendar = calendar & weekRow & vbCrLf
//!     End If
//!     
//!     GenerateCalendar = calendar
//! End Function
//!
//! Public Function GetAllMonthsForYear(abbreviate As Boolean) As String()
//!     Dim months() As String
//!     Dim i As Integer
//!     
//!     ReDim months(1 To 12)
//!     For i = 1 To 12
//!         months(i) = MonthName(i, abbreviate)
//!     Next i
//!     
//!     GetAllMonthsForYear = months
//! End Function
//! ```
//!
//! ### Example 2: Report Generator with Month Names
//!
//! ```vb
//! ' Class: MonthlyReportFormatter
//! ' Formats reports with localized month names
//!
//! Option Explicit
//!
//! Private m_useAbbreviations As Boolean
//! Private m_reportData As Collection
//!
//! Public Sub Initialize(useAbbrev As Boolean)
//!     m_useAbbreviations = useAbbrev
//!     Set m_reportData = New Collection
//! End Sub
//!
//! Public Sub AddMonthData(monthNum As Integer, dataValue As Double)
//!     Dim entry As String
//!     entry = MonthName(monthNum, m_useAbbreviations) & ":" & dataValue
//!     m_reportData.Add entry
//! End Sub
//!
//! Public Function GenerateReport() As String
//!     Dim report As String
//!     Dim item As Variant
//!     Dim i As Integer
//!     
//!     report = "Monthly Summary Report" & vbCrLf
//!     report = report & String(50, "-") & vbCrLf
//!     
//!     For Each item In m_reportData
//!         report = report & item & vbCrLf
//!     Next item
//!     
//!     GenerateReport = report
//! End Function
//!
//! Public Function FormatDateWithMonth(dateValue As Date) As String
//!     FormatDateWithMonth = MonthName(Month(dateValue), m_useAbbreviations) & _
//!                          " " & Day(dateValue) & ", " & Year(dateValue)
//! End Function
//!
//! Public Function GetQuarterMonths(quarter As Integer) As String
//!     Dim months As String
//!     Dim startMonth As Integer
//!     Dim i As Integer
//!     
//!     startMonth = ((quarter - 1) * 3) + 1
//!     
//!     For i = 0 To 2
//!         If i > 0 Then months = months & ", "
//!         months = months & MonthName(startMonth + i, m_useAbbreviations)
//!     Next i
//!     
//!     GetQuarterMonths = months
//! End Function
//! ```
//!
//! ### Example 3: Internationalized Date Formatter
//!
//! ```vb
//! ' Module: InternationalDateFormatter
//! ' Provides locale-aware date formatting using MonthName
//!
//! Option Explicit
//!
//! Public Enum DateFormat
//!     dfLong = 0          ' "January 15, 2025"
//!     dfMedium = 1        ' "Jan 15, 2025"
//!     dfShort = 2         ' "01/15/2025"
//!     dfMonthYear = 3     ' "January 2025"
//!     dfMonthYearShort = 4 ' "Jan 2025"
//! End Enum
//!
//! Public Function FormatDate(dateValue As Date, formatType As DateFormat) As String
//!     Select Case formatType
//!         Case dfLong
//!             FormatDate = MonthName(Month(dateValue)) & " " & _
//!                         Day(dateValue) & ", " & Year(dateValue)
//!         
//!         Case dfMedium
//!             FormatDate = MonthName(Month(dateValue), True) & " " & _
//!                         Day(dateValue) & ", " & Year(dateValue)
//!         
//!         Case dfShort
//!             FormatDate = Format(dateValue, "mm/dd/yyyy")
//!         
//!         Case dfMonthYear
//!             FormatDate = MonthName(Month(dateValue)) & " " & Year(dateValue)
//!         
//!         Case dfMonthYearShort
//!             FormatDate = MonthName(Month(dateValue), True) & " " & Year(dateValue)
//!     End Select
//! End Function
//!
//! Public Function FormatDateRange(startDate As Date, endDate As Date, _
//!                                abbreviate As Boolean) As String
//!     Dim result As String
//!     
//!     If Year(startDate) = Year(endDate) Then
//!         If Month(startDate) = Month(endDate) Then
//!             ' Same month and year
//!             result = MonthName(Month(startDate), abbreviate) & " " & _
//!                     Day(startDate) & "-" & Day(endDate) & ", " & Year(startDate)
//!         Else
//!             ' Different months, same year
//!             result = MonthName(Month(startDate), abbreviate) & " " & Day(startDate) & " - " & _
//!                     MonthName(Month(endDate), abbreviate) & " " & Day(endDate) & ", " & _
//!                     Year(endDate)
//!         End If
//!     Else
//!         ' Different years
//!         result = MonthName(Month(startDate), abbreviate) & " " & Day(startDate) & ", " & _
//!                 Year(startDate) & " - " & _
//!                 MonthName(Month(endDate), abbreviate) & " " & Day(endDate) & ", " & _
//!                 Year(endDate)
//!     End If
//!     
//!     FormatDateRange = result
//! End Function
//!
//! Public Function GetMonthNames(abbreviate As Boolean) As String()
//!     Dim months(1 To 12) As String
//!     Dim i As Integer
//!     
//!     For i = 1 To 12
//!         months(i) = MonthName(i, abbreviate)
//!     Next i
//!     
//!     GetMonthNames = months
//! End Function
//!
//! Public Function ParseMonthName(monthString As String) As Integer
//!     Dim i As Integer
//!     
//!     ' Try full names first
//!     For i = 1 To 12
//!         If UCase(MonthName(i)) = UCase(monthString) Then
//!             ParseMonthName = i
//!             Exit Function
//!         End If
//!     Next i
//!     
//!     ' Try abbreviated names
//!     For i = 1 To 12
//!         If UCase(MonthName(i, True)) = UCase(monthString) Then
//!             ParseMonthName = i
//!             Exit Function
//!         End If
//!     Next i
//!     
//!     ParseMonthName = 0 ' Not found
//! End Function
//! ```
//!
//! ### Example 4: Chart Label Generator
//!
//! ```vb
//! ' Class: ChartLabelGenerator
//! ' Generates chart labels with month names
//!
//! Option Explicit
//!
//! Private m_startMonth As Integer
//! Private m_monthCount As Integer
//! Private m_abbreviate As Boolean
//!
//! Public Sub Initialize(startMonth As Integer, monthCount As Integer, _
//!                       abbreviate As Boolean)
//!     If startMonth < 1 Or startMonth > 12 Then
//!         Err.Raise 5, "ChartLabelGenerator", "Invalid start month"
//!     End If
//!     
//!     m_startMonth = startMonth
//!     m_monthCount = monthCount
//!     m_abbreviate = abbreviate
//! End Sub
//!
//! Public Function GetLabels() As String()
//!     Dim labels() As String
//!     Dim i As Integer
//!     Dim currentMonth As Integer
//!     
//!     ReDim labels(0 To m_monthCount - 1)
//!     
//!     For i = 0 To m_monthCount - 1
//!         currentMonth = m_startMonth + i
//!         
//!         ' Wrap around if exceeds 12
//!         If currentMonth > 12 Then
//!             currentMonth = currentMonth - 12
//!         End If
//!         
//!         labels(i) = MonthName(currentMonth, m_abbreviate)
//!     Next i
//!     
//!     GetLabels = labels
//! End Function
//!
//! Public Function GetLabelWithYear(monthNum As Integer, yearNum As Integer) As String
//!     GetLabelWithYear = MonthName(monthNum, m_abbreviate) & " '" & _
//!                        Right(CStr(yearNum), 2)
//! End Function
//!
//! Public Function GetQuarterLabel(quarter As Integer, yearNum As Integer) As String
//!     Dim firstMonth As Integer
//!     firstMonth = ((quarter - 1) * 3) + 1
//!     
//!     GetQuarterLabel = "Q" & quarter & " (" & _
//!                      MonthName(firstMonth, True) & "-" & _
//!                      MonthName(firstMonth + 2, True) & " " & _
//!                      yearNum & ")"
//! End Function
//!
//! Public Function GetYearLabels(abbreviate As Boolean) As String()
//!     Dim labels(1 To 12) As String
//!     Dim i As Integer
//!     
//!     For i = 1 To 12
//!         labels(i) = MonthName(i, abbreviate)
//!     Next i
//!     
//!     GetYearLabels = labels
//! End Function
//!
//! Public Function FormatMultiYearLabel(monthNum As Integer, _
//!                                     startYear As Integer, _
//!                                     endYear As Integer) As String
//!     FormatMultiYearLabel = MonthName(monthNum, m_abbreviate) & " " & _
//!                           startYear & "-" & endYear
//! End Function
//! ```
//!
//! ## Error Handling
//!
//! ```vb
//! On Error Resume Next
//! monthName = MonthName(monthNum)
//! If Err.Number = 5 Then
//!     MsgBox "Invalid month number. Must be between 1 and 12."
//! ElseIf Err.Number <> 0 Then
//!     MsgBox "Error getting month name: " & Err.Description
//! End If
//! On Error GoTo 0
//! ```
//!
//! ## Performance Considerations
//!
//! - `MonthName()` is very fast - simple lookup operation
//! - For repeated calls, consider caching month name arrays
//! - No performance difference between full and abbreviated names
//! - Locale lookup may add minimal overhead but is negligible
//! - More efficient than maintaining hardcoded month name arrays
//! - Can be called millions of times without performance concerns
//!
//! ## Best Practices
//!
//! 1. **Validate month numbers** - Always check that month is 1-12 before calling
//! 2. **Use for localization** - Leverages system locale for international support
//! 3. **Combine with `Month()`** - Extract month number from dates, then get name
//! 4. **Consider abbreviations** - Use abbreviated names for space-constrained displays
//! 5. **Cache for UI** - Populate drop-downs once, not on every refresh
//! 6. **Document format** - Clearly state whether full or abbreviated names are expected
//! 7. **Test locales** - Test with different regional settings for international apps
//! 8. **Handle errors** - Wrap in error handling for robust code
//! 9. **Use constants** - Define month number constants for readability
//! 10. **Prefer over arrays** - Use `MonthName()` instead of hardcoded name arrays
//!
//! ## Comparison with Other Approaches
//!
//! | Approach | Pros | Cons |
//! |----------|------|------|
//! | **`MonthName()`** | Automatic localization, simple, no maintenance | Requires VBA/VB6, slightly slower than array |
//! | **Hardcoded array** | Fast, full control | No localization, maintenance burden |
//! | **`Format()`** | Flexible formatting | Returns different formats, not just name |
//! | **`DatePart()`** | Returns number, not name | Need to convert to name separately |
//!
//! ## Localization Notes
//!
//! The `MonthName` function returns month names based on the system's regional settings:
//! - **English (US)**: "January", "February", etc. / "Jan", "Feb", etc.
//! - **Spanish**: "enero", "febrero", etc. / "ene", "feb", etc.
//! - **French**: "janvier", "février", etc. / "janv", "févr", etc.
//! - **German**: "Januar", "Februar", etc. / "Jan", "Feb", etc.
//! - **Japanese**: "1月", "2月", etc.
//! - And many more locales...
//!
//! ## Platform Notes
//!
//! - Available in VBA (Excel, Access, Word, etc.)
//! - Available in VB6
//! - **Not available in `VBScript`** (`VBScript` lacks this function)
//! - Returns String type
//! - Consistent across all VBA platforms
//! - Uses Control Panel regional settings
//! - First introduced in VB6 and VBA 6.0
//!
//! ## Limitations
//!
//! - Month parameter must be 1-12 (no 0 or 13+)
//! - Error 5 if month is out of valid range
//! - Returns names based on system locale only (cannot specify locale)
//! - Abbreviated length varies by locale (usually 3 chars, but not always)
//! - Not available in `VBScript`
//! - Cannot customize the returned names
//!
//! ## Related Functions
//!
//! - **Month** - Returns the month number (1-12) from a date
//! - **`WeekdayName`** - Returns the name of the weekday (similar function for days)
//! - **Format** - Can format dates with month names using format strings
//! - **`DatePart`** - Returns various parts of a date (including month number)
//! - **Year** - Returns the year component of a date
//! - **Day** - Returns the day component of a date
//!
//! ## VB6 Parser Notes
//!
//! `MonthName` is parsed as a regular function call (`CallExpression`). This module exists primarily
//! for documentation purposes to provide comprehensive reference material for VB6 developers
//! working with date formatting and display operations requiring localized month names.

use crate::error::{VBError, VBResult};
use crate::value::{VBBoolean, VBLong, VBString};

const FULL_NAMES: [&str; 12] = [
    "January",
    "February",
    "March",
    "April",
    "May",
    "June",
    "July",
    "August",
    "September",
    "October",
    "November",
    "December",
];

const ABBREVIATED_NAMES: [&str; 12] = [
    "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
];

/// Implementation of the `MonthName` function.
///
/// VB6 behavior:
/// - a month outside 1..=12 raises error 5 (invalid procedure call)
/// - the `abbreviate` argument is optional and defaults to False (full name)
/// - a non-numeric month raises error 13 (type mismatch); `Null` raises
///   error 94 (invalid use of Null)
pub fn month_name(month: &VBLong, abbreviate: Option<&VBBoolean>) -> VBResult<VBString> {
    let month = month.as_i32();
    if !(1..=12).contains(&month) {
        return Err(VBError::invalid_procedure_call());
    }
    let abbreviate = abbreviate.is_some_and(|v| v.as_bool());
    let index = (month - 1) as usize;
    let name = if abbreviate {
        ABBREVIATED_NAMES[index]
    } else {
        FULL_NAMES[index]
    };
    Ok(VBString::from(name))
}

#[cfg(test)]
mod tests {
    use super::{month_name, ABBREVIATED_NAMES, FULL_NAMES};
    use crate::error::err_number;
    use crate::value::{VBBoolean, VBLong, VBVariant};
    use std::convert::TryFrom;

    fn n(input: &VBVariant) -> String {
        month_name(&VBLong::try_from(input).unwrap(), None)
            .unwrap()
            .as_str()
            .to_string()
    }

    fn na(input: &VBVariant, abbreviate: &VBVariant) -> String {
        month_name(
            &VBLong::try_from(input).unwrap(),
            Some(&VBBoolean::try_from(abbreviate).unwrap()),
        )
        .unwrap()
        .as_str()
        .to_string()
    }

    #[test]
    fn full_names() {
        for (i, name) in FULL_NAMES.iter().enumerate() {
            assert_eq!(n(&VBVariant::from_long(i as i32 + 1)), *name);
        }
    }

    #[test]
    fn abbreviated_names() {
        for (i, name) in ABBREVIATED_NAMES.iter().enumerate() {
            assert_eq!(
                na(
                    &VBVariant::from_long(i as i32 + 1),
                    &VBVariant::from_bool(true)
                ),
                *name
            );
        }
    }

    #[test]
    fn abbreviate_defaults_to_false() {
        assert_eq!(n(&VBVariant::from_long(1)), "January");
    }

    #[test]
    fn abbreviate_accepts_numeric_values() {
        assert_eq!(
            na(&VBVariant::from_long(2), &VBVariant::from_long(1)),
            "Feb"
        );
        assert_eq!(
            na(&VBVariant::from_long(2), &VBVariant::from_long(-1)),
            "Feb"
        );
        assert_eq!(
            na(&VBVariant::from_long(2), &VBVariant::from_long(0)),
            "February"
        );
    }

    #[test]
    fn abbreviate_accepts_string_values() {
        assert_eq!(
            na(&VBVariant::from_long(3), &VBVariant::from_string("true")),
            "Mar"
        );
        assert_eq!(
            na(&VBVariant::from_long(3), &VBVariant::from_string("false")),
            "March"
        );
    }

    #[test]
    fn month_out_of_range_is_error_5() {
        for bad in [0, -1, 13] {
            let err = month_name(&VBLong::from(bad), None).unwrap_err();
            assert_eq!(err.number, err_number::INVALID_PROCEDURE_CALL);
        }
    }

    #[test]
    fn null_month_is_error_94() {
        let err = VBLong::try_from(&VBVariant::Null).unwrap_err();
        assert_eq!(err.number, err_number::INVALID_USE_OF_NULL);
    }

    #[test]
    fn non_numeric_month_is_error_13() {
        let err = VBLong::try_from(&VBVariant::from_string("abc")).unwrap_err();
        assert_eq!(err.number, err_number::TYPE_MISMATCH);
    }

    #[test]
    fn returns_vbstring() {
        let result = month_name(&VBLong::from(12), None).unwrap();
        assert_eq!(result.as_str(), "December");
    }
}