﻿Imports Superbowl_Daily_2.SystemFunctions
Imports Superbowl_Daily_2.ProjectFunctions
Imports Superbowl_Daily_2.db
Imports Superbowl_Daily_2.dataExport
Imports System.IO
Imports Microsoft.VisualBasic

'20140220 - v2.0.1 - added AdvM pda export files - pj & dwayne
'20190910 - updated max progress bar value - maanie

Public Class Export_Process
   Public Name, ID, Filename, Path, SQL As String
   Public doProcess, isValid As Boolean
   Public intRecordsTotal, intRecordsExported As Integer
   'Public PK As List(Of KeyValuePair(Of String, String))
   Public PK As String()
   Public barProcess As ProgressBar

   Public srExport As IO.StreamReader
   Public fiExport As IO.FileInfo

   Dim ds As DataSet


   Public Sub New(Name As String, Filename As String, Path As String, strSQL As String)
      Me.Name = Name
      Me.ID = Name.Replace(" ", "")
      Me.Filename = Filename
      Me.Path = Path
      Me.SQL = strSQL

      intRecordsTotal = intRecordsExported = 0

      Me.doProcess = True

   End Sub

   Public Sub Run()
      '1 ini & log
      '2 create local file [run sql]
      '3 upload local file
      '4 log complete

      '1 ini & log: ini get #records

      Me.LogProcessStart()

      Dim dr As DataRow
      Dim idxOrderBy As Integer = Me.SQL.ToUpper.LastIndexOf("ORDER BY")
      Dim sqlIni As String
      If idxOrderBy > -1 Then
         sqlIni = "SELECT COUNT(*) AS intCount FROM (" & Me.SQL.Substring(0, idxOrderBy) & ") as tblCount"
      Else
         sqlIni = "SELECT COUNT(*) AS intCount FROM (" & Me.SQL & ") as tblCount"
      End If

      dr = db.getRow(sqlIni)
      If Not dr Is Nothing Then
         Me.intRecordsTotal = dr!intCount
      End If

      Me.setProgress()

      '2 create local file [run sql]
      Dim blnComplete As Boolean = Me.ExportLocalFile()

      '3 upload local file
      If blnComplete = True Then
         Me.barProcess.BackColor = Color.DarkOrchid
         Me.barProcess.Style = ProgressBarStyle.Continuous
         Me.barProcess.Refresh()

         Me.UploadFile()
      Else
         Me.barProcess.BackColor = Color.DarkRed
         Me.barProcess.Style = ProgressBarStyle.Blocks
         Me.barProcess.Refresh()

      End If

      '4 log complete
      Me.LogProcessCompleted()

   End Sub

   Public Function ExportLocalFile() As Boolean
      'run sql
      WriteLog("info", Me.Name, "File Export", "Export Start: {0/" & Me.intRecordsTotal & "}")
      ds = db.doQuery(Me.SQL)

      'ini export cls
      Dim myExport As New dataExport(ds.Tables(0), My.Settings.dirExports & Me.Filename, Me, Me.Name)
      'go
      myExport.Execute()
      If myExport.blnError = True Then
         WriteLog("warning", Me.Name, "File Export", "Export Failed: " & myExport.Message)
         Return False
      Else
         WriteLog("info", Me.Name, "File Export", "Export Completed: {" & myExport.intRecordsExported & "/" & Me.intRecordsTotal & " records exported to " & myExport.Filename & "}")
         Return True
      End If

   End Function

   Public Sub UploadFile()
      'log "File Download"
      Try

         If File.Exists(My.Settings.dirExports & Me.Filename) Then
            File.Copy(My.Settings.dirExports & Me.Filename, Me.Path & Me.Filename, True)
            WriteLog("info", Me.Name, "File Upload", "File uploaded to " & Me.Path & Me.Filename)
         Else
            WriteLog("warning", Me.Name, "File Upload", "Upload directory not found! [" & My.Settings.dirExports & Me.Filename & "]")
         End If
      Catch ex As Exception
         WriteLog("error", Me.Name, "File Upload", "Error uploading file! [" & ex.Message & Chr(13) & Chr(10) & ex.StackTrace & "]")
      End Try

   End Sub

   'Public Sub CreateLocalExportFile()
   '   'log "File Import"
   '   'note, this function has to be at the child level, because we need to call the child.sqlInsertStaging()
   '   'ini
   '   Dim fileImport As Object
   '   Dim intRecord As Integer
   '   Dim sql As String

   '   fileImport = New FileIO.TextFieldParser(Me.fiImport.FullName)
   '   WriteLog("info", Me.Name, "File Import", "Import Start: {0/" & Me.intRecordsTotal & "}")

   '   'setup csv/text
   '   Select Case Me.fiImport.Extension
   '      Case ".csv" 'http://stackoverflow.com/questions/736629/parse-delimited-csv-in-net
   '         fileImport.TextFieldType = FileIO.FieldType.Delimited
   '         fileImport.Delimiters = New String() {","}
   '         fileImport.HasFieldsEnclosedInQuotes = True

   '      Case Else
   '         WriteLog("error", Me.Name, "File Import", "Error reading record! Unsupported file type [" & Me.fiImport.FullName & "]")
   '         Me.isValid = False
   '         Exit Sub

   '   End Select

   '   'read data line by line
   '   Dim drImport As String()

   '   'read header:
   '   drImport = fileImport.ReadFields()
   '   intRecord += 1

   '   'read the rest
   '   While Not fileImport.endOfData
   '      Try
   '         'ini
   '         drImport = fileImport.ReadFields()
   '         intRecord += 1

   '         'process: note that the sqlInsertSTG get overriden in the child entity
   '         sql = Me.sqlInsertStaging(drImport)
   '         db.doQuery(sql)

   '      Catch icEx As InvalidCastException
   '         WriteLog("warning", Me.Name, "File Import", "Invalid record: [" & icEx.Message & "] {" & intRecord & "/" & Me.intRecordsTotal & "}")
   '      Catch sqlEx As System.Data.SqlClient.SqlException
   '         If intRecord > 1 Then 'ln 1 might be the file headings
   '            WriteLog("warning", Me.Name, "File Import", "Error reading record: [" & sqlEx.Message & " :: " & sql & "] {" & intRecord & "/" & Me.intRecordsTotal & "}")
   '         End If
   '      Catch mlEx As FileIO.MalformedLineException
   '         WriteLog("warning", Me.Name, "File Import", "Error reading record: Malformed data record! [" & mlEx.Message & "] {" & intRecord & "/" & Me.intRecordsTotal & "}")
   '      Catch ex As Exception
   '         WriteLog("error", Me.Name, "File Import", "Error reading record! [" & ex.Message & "] {" & intRecord & "/" & Me.intRecordsTotal & "}")

   '      Finally
   '         'post
   '         Me.Progress()

   '      End Try

   '   End While

   '   Dim dr As DataRow = db.getRow("SELECT count(*) as intRecords FROM " & Me.tblStaging)
   '   WriteLog("info", Me.Name, "File Import", "Import Completed: {" & dr!intRecords & "/" & Me.intRecordsTotal & " records imported}")

   'End Sub

   Public Sub setProgress()

      If Me.intRecordsTotal > 0 Then
         Me.barProcess.Maximum = Me.intRecordsTotal ' - 10 '20190910 - updated max progress bar value - maanie
         Me.barProcess.Value = 0
      End If
   End Sub

   Public Sub Progress()

      Try
         'If Me.barProcess.Value < Me.barProcess.Maximum Then
         Me.barProcess.PerformStep()
         If Me.barProcess.Value Mod 10 = 0 Then
            Me.barProcess.Refresh()
         End If
         'End If
      Catch ex As Exception
         Me.barProcess.Value = Me.barProcess.Maximum
      End Try
   End Sub

   Public Sub LogProcessStart()
      WriteLog("info", Me.Name, "Process Start", "Process Start: " & Date.Now.ToString("u"))
   End Sub

   Public Sub LogProcessCompleted()
      WriteLog("info", Me.Name, "Process Completed", "Process Completed: " & Date.Now.ToString("u"))
   End Sub

End Class

