Imports System.Runtime.InteropServices
Imports System
Imports System.IO
Imports System.Text




Public Class Form1
    Public strIniFilePath As String = String.Empty
    Public strMajorSolidEdgeVersion As String = String.Empty
    Public strFullNameOfIniFile As String = String.Empty
    Public strNumberGeneratorFile As String = String.Empty
    Public intNumberOfDigits As Integer = 0
    Public strNumberOfDigits As String = String.Empty

    Public strPulledPrefix As String = String.Empty
    Public intMaxTries As Integer = 0
  

    Public Function oGetThisApplicationPath() As String
        Return My.Application.Info.DirectoryPath
    End Function
    Public Function oIsValidFileName(ByVal fn As String) As Boolean
        Try
            If System.IO.File.Exists(fn) Then
                Return True
            Else
                Return False
            End If
        Catch ex As Exception
            Return False
        End Try
    End Function

    Sub oReleaseObject(ByVal obj As Object)
        Try
            If Not (obj Is Nothing) Then
                'this should only be used when programming applications that run in their own process space
                Marshal.FinalReleaseComObject(obj)
            End If
        Catch ex As Exception
            obj = Nothing
        End Try
    End Sub
    Public Sub oForceGarbageCollection()
        Try
            GC.Collect(GC.MaxGeneration())
            GC.WaitForPendingFinalizers()
            GC.Collect(GC.MaxGeneration())
        Catch ex As Exception

        End Try
    End Sub
    
    Public Function oReadIniFile(ByVal oFilename As String, ByVal strLineContaining As String) As String
        Try
            Dim arrData As String() = System.IO.File.ReadAllLines(oFilename)
            Dim strData As String

            For Each strData In arrData
                If strData = "" Then
                    Continue For
                End If
                If InStr(strData.ToUpper, "#", Microsoft.VisualBasic.CompareMethod.Text) <> 0 Then
                    GoTo skip
                End If

                If InStr(strData.ToUpper, strLineContaining.ToUpper, Microsoft.VisualBasic.CompareMethod.Text) <> 0 Then
                    Dim arrStrDataSplit As String() = strData.Split("=")
                    Return arrStrDataSplit(1)
                End If
skip:
            Next

        Catch ex As Exception
            Return Nothing
        End Try


        Return Nothing
    End Function

    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles Me.Load

        Try
            'get the path of this executable.  The INI file should be in the same location!
            strIniFilePath = oGetThisApplicationPath()

            'set the ini filename
            strFullNameOfIniFile = "NumberGenerator.ini"

            strFullNameOfIniFile = strIniFilePath + "\" + strFullNameOfIniFile

            'check to make sure the ini file is present
            If oIsValidFileName(strFullNameOfIniFile) = True Then
                strNumberGeneratorFile = oReadIniFile(strFullNameOfIniFile, "PATH=")
                strPulledPrefix = oReadIniFile(strFullNameOfIniFile, "PREFIX=")
            Else
                MessageBox.Show("Can not find the file " + strFullNameOfIniFile + " exiting the utility!", "Number Generator", MessageBoxButtons.OK)
                End
            End If

            'populate the dialog with the prefix pulled from local ini file
            If strPulledPrefix IsNot String.Empty Then
                Me.TextBoxPrefix.Text = strPulledPrefix
            End If

            'check to see how many digits the auto incremented number contains
            strNumberOfDigits = CountLengthOfPartNumber(strNumberGeneratorFile)
            intMaxTries = 0
            If strNumberOfDigits = "locked" Then
                System.Threading.Thread.Sleep(1000)
                strNumberOfDigits = CountLengthOfPartNumber(strNumberGeneratorFile)
                Do While intMaxTries < 6 And strNumberOfDigits = "locked"
                    If intMaxTries = 5 Then
                        MessageBox.Show("Could not determine the length of the part number to be incremented!", "Number Generator", MessageBoxButtons.OK)
                        End
                    End If
                    System.Threading.Thread.Sleep(1000)
                    strNumberOfDigits = CountLengthOfPartNumber(strNumberGeneratorFile)
                    intMaxTries = intMaxTries + 1
                Loop
            End If

            If strNumberOfDigits <> String.Empty Then
                intNumberOfDigits = strNumberOfDigits.Length
            End If
        Catch ex As Exception
            MessageBox.Show("Error encountered on form load " + ex.Message, "Number Generator", MessageBoxButtons.OK)
        End Try





    End Sub

    Private Sub Button2_Click(sender As Object, e As EventArgs)
        End
    End Sub

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
       
        Dim strNewNumber As String = String.Empty

        Try
            intMaxTries = 0

            Me.TextBoxPulledNumberToAssign.Text = String.Empty
            Me.TextBoxPulledNumberToAssign.Refresh()

            strNewNumber = PullNewPartNumber()
            If strNewNumber = "locked" Then
                System.Threading.Thread.Sleep(1000)
                strNewNumber = PullNewPartNumber()
                Do While intMaxTries < 6 And strNewNumber = "locked"
                    If intMaxTries = 5 Then
                        strNewNumber = "locked..try again!"
                        Exit Do
                    End If
                    System.Threading.Thread.Sleep(1000)
                    strNewNumber = PullNewPartNumber()
                    intMaxTries = intMaxTries + 1
                Loop
            End If

            Me.TextBoxPulledNumberToAssign.Text = strNewNumber
            Me.TextBoxPulledNumberToAssign.Refresh()

            'now add the value to the clipboard
            My.Computer.Clipboard.SetText(Trim(Me.TextBoxPrefix.Text + strNewNumber))

            'now write back the prefix if it changed... to the local INI file.
            If strPulledPrefix <> Me.TextBoxPrefix.Text Then
                Dim arrData As String() = System.IO.File.ReadAllLines(strFullNameOfIniFile)
                Dim ii As Integer = 0
                For ii = 0 To arrData.Length - 1
                    If InStr(arrData(ii), "PREFIX=", Microsoft.VisualBasic.CompareMethod.Text) <> 0 Then
                        arrData(ii) = "PREFIX=" + Me.TextBoxPrefix.Text
                        Exit For
                    End If
                Next
                System.IO.File.WriteAllLines(strFullNameOfIniFile, arrData)
            End If
        Catch ex As Exception
            MessageBox.Show("Error encountered " + ex.Message, "Number Generator", MessageBoxButtons.OK)
        End Try



        'code below will strike through text
        'Me.TextBoxPulledNumberToAssign.Font = New Font("Microsoft Sans Serif", 7.8, FontStyle.Strikeout)



    End Sub
    

    Public Function PullNewPartNumber() As String
        Dim strRead As String = String.Empty

        Try

        
            Using fs As FileStream = File.Open(strNumberGeneratorFile, FileMode.Open, FileAccess.ReadWrite, FileShare.None)
                Dim strNewValue As String

                If fs.CanRead = False Then
                    Return "locked"
                End If
                Dim b(1024) As Byte
                Dim temp As UTF8Encoding = New UTF8Encoding(True)

                Do While fs.Read(b, 0, b.Length) > 0
                    strRead = temp.GetString(b).ToString
                Loop


                Dim intNewValue As Long = 0
                intNewValue = CLng(strRead) + 1
                strNewValue = FormatValue(intNewValue, intNumberOfDigits)

                'now write the incremented value back to the text file
                Dim info As Byte() = New UTF8Encoding(True).GetBytes(strNewValue)
                fs.Position = 0
                fs.Write(info, 0, info.Length)

                fs.Close()
                Return strRead
            End Using
        Catch ex As Exception
            Return "locked"
        End Try

    End Function

    Public Function CountLengthOfPartNumber(ofile As String) As String

        Dim pullarray() As String

        Try
            pullarray = System.IO.File.ReadAllLines(ofile)
            If pullarray.Count > 0 Then
                Return pullarray(0)
                Exit Function
            Else
                Return "Locked"
            End If

        Catch ex As Exception
            Return "locked"
        End Try
        Return "locked"

    End Function

    Public Function FormatValue(intInput As Integer, intNumberOfDigits As Integer) As String

        Try
            Dim strinput As String = CStr(intInput)

            Do While Len(strinput) <> intNumberOfDigits
                strinput = "0" + strinput
            Loop

            Return strinput
        Catch ex As Exception
            Return String.Empty
        End Try


    End Function
End Class
