Imports System.Collections.Generic
Imports System.Linq
Imports System.Web
Imports C1.Win.C1Document
Imports System.Collections.Specialized
Imports C1.Win.FlexReport
Imports C1.Web.Api.Report.Models
Imports C1.Web.Api.Report

Public Class MemoryReportsProvider
    Inherits ReportProvider
    ''' <summary>
    ''' Gets children of the specified folder.
    ''' </summary>
    ''' <param name="providerName">The key used to register the provider.</param>
    ''' <param name="path">The relative path of the folder.</param>
    ''' <param name="recursive">Whether to return the entire tree of child items below the specified item.</param>
    ''' <param name="args">The collection of HTTP query string variables.</param>
    ''' <returns>Array of <see cref="CatalogItem"/>.</returns>
    Public Overrides Function ListChildren(providerName As String, path As String, recursive As Boolean, Optional args As NameValueCollection = Nothing) As CatalogItem()
        ' this method is used by reports controller.
        Throw New NotSupportedException()
    End Function

    ''' <summary>
    ''' Creates the document for the specified report path.
    ''' </summary>
    ''' <param name="path">The relative path of the report, without the registered key for the report provider.</param>
    ''' <param name="args">The collection of HTTP query string variables.</param>
    ''' <returns>A <see cref="C1DocumentSource"/> created for the specified path.</returns>
    Protected Overrides Function CreateDocument(path As String, args As NameValueCollection) As C1DocumentSource
        ' in this sample, the path is "ReportsRoot/DataSourceInMemory.flxr/Simple List".

        Dim index = path.LastIndexOf("/")
        Dim filePath = path.Substring(0, index)
        Dim reportName = path.Substring(index + 1)
        Dim fileName = System.IO.Path.Combine(AppDomain.CurrentDomain.SetupInformation.ApplicationBase, filePath)

        Dim report = New C1FlexReport()
        report.Load(fileName, reportName)
        UpdateDataSource(report, args)
        Return report
    End Function

    Private Sub UpdateDataSource(report As C1FlexReport, args As NameValueCollection)
        If report Is Nothing OrElse args Is Nothing Then
            Return
        End If

        Dim country = args("country")
        Dim dataset = Employees.DataSet
        Dim datatable = If(country IsNot Nothing AndAlso dataset.Tables.Contains(country), dataset.Tables(country), dataset.Tables(0))

        report.DataSource.Recordset = datatable
    End Sub
End Class