Imports System.Data
Imports System.Data.SqlClient
Imports System.IO
Imports System.IO.Ports

Public Class mountingForm

    Public mountStart As Boolean = False
    Public status As Boolean = False
    Public mountAfter As Boolean = False
    Public reload As Boolean = False
    Public match As Boolean = True
    Public qacheck As Boolean = False
    Public notissued As Boolean = False
    Public wrongline As Boolean = False
    Public mismatch As Boolean = False

    Private sequence As New Sequence()
    Private currentsequence As String
    Private currentrev As String
    Private currentline As String
    Private currentmodel As String
    Private currenttype As String
    Private verificationTime As DateTime
    Private expirationDate As DateTime
    Private isQA As Boolean = False
    Private isVerification As Boolean = False
    Private kseqno As String
    Public mounted As Boolean = False
    Private checkVerification As Boolean = True
    Dim proceed As Boolean
    Private cnstr As String

    Private Sub mountingForm_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Me.MdiParent = mainForm
        Control.CheckForIllegalCrossThreadCalls = False
        getSequence()
        Timer1.Interval = 500
        Timer1.Start()
        Timer1.Enabled = False
        btn_reload.Enabled = False
        btn_Check.Enabled = False
        btnComplete.Visible = False
        dg.Visible = False

        initializeDG()
        Timer3.Start()

        'Dim cnstr = mainForm.cnstr
        'Dim conn As New SqlConnection(cnstr)
        'Dim myQuery As String
        'myQuery = "SELECT * FROM KPORT WHERE line = '" & cmbLine.Text & "'"

        'Dim mycommand As SqlCommand
        'mycommand = New SqlCommand(myQuery, conn)
        'Dim spdate As Date

        'Try
        '    conn.Open()
        '    Dim reader As SqlDataReader = mycommand.ExecuteReader()
        '    reader.Read()
        '    Dim comport As String
        '    comport = reader("KPortnum")
        '    conn.Close()
        '    spdate = lbldo.Text
        '    lbled.Text = spdate.AddDays(2)


        'SerialPort1.Close()
        'SerialPort1.PortName = comport
        'SerialPort1.BaudRate = 9600
        'SerialPort1.DataBits = 8
        'SerialPort1.Parity = Parity.None
        'SerialPort1.StopBits = StopBits.One
        'SerialPort1.Handshake = Handshake.None
        '    SerialPort1.Encoding = System.Text.Encoding.Default

        'Catch ex As Exception
        '    'MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
        'End Try
        'conn.Close()


    End Sub

    Private Sub getSequence()
        Dim sequence As New Sequence
        Dim sequenceList As New List(Of String)
        Dim i As Integer = 0

        cmbRev.Items.Clear()
        sequenceList = sequence.getValidSequence()
        cmbSeq.Items.Clear()
        While i < sequenceList.Count
            cmbSeq.Items.Add(sequenceList(i))
            i = i + 1
        End While
    End Sub

    Public Sub getRevisions()
        Dim rev As New Sequence
        Dim revList As New List(Of String)
        Dim i As Integer = 0

        revList = rev.getRevisions(cmbSeq.SelectedItem, cmbLine.SelectedItem, cmbModel.SelectedItem, cmbType.SelectedItem)
        cmbRev.Items.Clear()
        While i < revList.Count
            cmbRev.Items.Add(revList(i))
            i = i + 1
        End While
    End Sub

    Public Sub getModels()
        Dim rev As New Sequence
        Dim revList As New List(Of String)
        Dim i As Integer = 0

        revList = rev.getModel(cmbSeq.SelectedItem, cmbLine.SelectedItem)
        cmbModel.Items.Clear()
        While i < revList.Count
            cmbModel.Items.Add(revList(i))
            i = i + 1
        End While
    End Sub

    Public Sub getTypes()
        Dim rev As New Sequence
        Dim revList As New List(Of String)
        Dim i As Integer = 0

        revList = rev.getTypes(cmbSeq.SelectedItem, cmbLine.SelectedItem, cmbModel.SelectedItem)
        cmbType.Items.Clear()
        While i < revList.Count
            cmbType.Items.Add(revList(i))
            i = i + 1
        End While
    End Sub

    Public Sub getLines()
        Dim rev As New Sequence
        Dim revList As New List(Of String)
        Dim i As Integer = 0

        revList = rev.getLines(cmbSeq.SelectedItem)
        cmbLine.Items.Clear()
        While i < revList.Count
            cmbLine.Items.Add(revList(i))
            i = i + 1
        End While
    End Sub

    Private Sub txtStart_KeyUp(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles txtStart.KeyUp
        If e.KeyCode = Keys.Enter Then
            Dim fChar As String = String.Empty
            Dim entry As String = txtStart.Text
            Dim str() As String



            If mountAfter = True Then
                clear()
                mountAfter = False
                Timer1.Enabled = False
                lbl_Pass.Visible = False
                lbl_fail.Visible = False
                lblMatch.Visible = False
            End If

            fChar = Mid(entry, 1, 1)

            If (reload) Then

                If entry.Contains("*") Then
                    txtFeeder.Text = entry.Replace("*", "")
                    txtStart.Text = String.Empty
                    txtStart.Focus()
                ElseIf fChar = "@" Then
                    txtOperator.Text = Mid(entry, 2, Len(entry))
                    txtStart.Text = String.Empty
                    txtStart.Focus()
                    ' ElseIf (IsNumeric(entry) And Len(entry) <> 15) Then
                    '    txtQuantity.Text = entry
                    '   txtStart.Text = String.Empty
                    '    txtStart.Focus()
                ElseIf IsSerialNumber(entry, isVerification, cmbLine.SelectedItem.ToString) And txtFeeder.Text.Length > 0 Then
                    Dim mount As New Mounting()
                    str = Split(txtFeeder.Text, "-")
                    If Not entry.StartsWith("LA") Then

                        txtSerial.Text = entry.Substring(0, 10)
                    Else

                        txtSerial.Text = entry
                    End If
                    Dim parts As New PartsRecords(txtSerial.Text)
                    txtPartNo.Text = parts.IonicsPN

                    txtPartDesc.Text = parts.Description
                    txtLotNum.Text = parts.LotNo
                    txtQuantity.Text = parts.Quantity
                    lblstatus.Text = parts.Status
                    txtStart.Text = String.Empty
                    txtStart.Focus()

                    If lblstatus.Text = "PDN" Then
                        Label15.Text = "Date Registered: "
                    Else
                        Label15.Text = "Date Open: "
                    End If

                    If txtPartNo.Text = "M705PCIS4000" Or "GY4CS000P110" And lblstatus.Text = "SMT" Then
                        Dim cnstr = mainForm.cnstr
                        Dim conn As New SqlConnection(cnstr)
                        Dim myQuery As String
                        myQuery = "SELECT * FROM PartsLog WHERE MaterialID = '" & txtSerial.Text & "' and status = 'Mounted' order by lastupdated asc"

                        Dim mycommand As SqlCommand
                        mycommand = New SqlCommand(myQuery, conn)
                        Dim spdate As Date

                        Try
                            conn.Open()
                            Dim reader As SqlDataReader = mycommand.ExecuteReader()
                            reader.Read()
                            Dim NextTime As Date
                            NextTime = NextTime.AddDays(2)
                            spdid.Text = reader("MaterialID")
                            splotno.Text = reader("LotNo")
                            lbldo.Text = reader("lastupdated")
                            conn.Close()
                            spdate = lbldo.Text
                            lbled.Text = spdate.AddDays(2)

                            If lbled.Text <= Date.Now Then
                                proceed = True
                                NotificationForm.text = "48 HOURS EXPIRED SOLDER PASTE"
                                NotificationForm.ShowDialog()

                            Else
                                proceed = False
                            End If
                        Catch ex As Exception
                            'MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
                        End Try
                        conn.Close()

                    ElseIf txtPartNo.Text = "M705PCIS4000" Or "GY4CS000P110" And lblstatus.Text = "PDN" Then

                        Dim cnstr = mainForm.cnstr
                        Dim conn As New SqlConnection(cnstr)
                        Dim myQuery As String
                        myQuery = "SELECT * FROM PartsLog WHERE MaterialID = '" & txtSerial.Text & "' and status = 'Issued' order by lastupdated asc"

                        Dim mycommand As SqlCommand
                        mycommand = New SqlCommand(myQuery, conn)
                        Dim spdate As Date

                        Try
                            conn.Open()
                            Dim reader As SqlDataReader = mycommand.ExecuteReader()
                            reader.Read()
                            Dim NextTime As Date
                            NextTime = NextTime.AddDays(3)
                            spdid.Text = reader("MaterialID")
                            splotno.Text = reader("LotNo")
                            lbldo.Text = reader("lastupdated")
                            conn.Close()
                            spdate = lbldo.Text
                            lbled.Text = spdate.AddDays(3)

                            If lbled.Text <= Date.Now Then
                                proceed = True
                                NotificationForm.text = "72 HOURS EXPIRED SOLDER PASTE"
                                NotificationForm.ShowDialog()

                            Else
                                proceed = False
                            End If
                        Catch ex As Exception
                            'MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
                        End Try
                        conn.Close()

                    Else
                        proceed = False

                    End If


                    If (proceed = False) Then

                        If (mount.checkOldLabel(txtPartNo.Text, txtSerial.Text, str(0), str(1), cmbRev.SelectedItem.ToString, kseqno)) Then
                            match = True
                            mismatch = False
                        Else
                            match = False
                            mismatch = True
                        End If
                    End If
                End If

            Else

                If entry.Contains("*") Then
                    txtFeeder.Text = entry.Replace("*", "")
                    str = Split(txtFeeder.Text, "-")
                    txtStart.Text = String.Empty
                    txtStart.Focus()
                ElseIf fChar = "@" Then
                    txtOperator.Text = Mid(entry, 2, Len(entry))
                    txtStart.Text = String.Empty
                    txtStart.Focus()
                    ' ElseIf (IsNumeric(entry) And Len(entry) <> 15) Then
                    '    txtQuantity.Text = entry
                    '   txtStart.Text = String.Empty
                    '    txtStart.Focus()
                ElseIf IsSerialNumber(entry, isVerification, cmbLine.SelectedItem.ToString) Then

                    If Not entry.StartsWith("LA") Then

                        txtSerial.Text = entry.Substring(0, 10)
                    Else

                        txtSerial.Text = entry
                    End If
                    Dim parts As New PartsRecords(txtSerial.Text)
                    txtPartNo.Text = parts.IonicsPN
                    txtPartDesc.Text = parts.Description
                    txtLotNum.Text = parts.LotNo
                    txtQuantity.Text = parts.Quantity
                    lblstatus.Text = parts.Status
                    txtStart.Text = String.Empty
                    txtStart.Focus()

                    If lblstatus.Text = "PDN" Then
                        Label15.Text = "Date Registered: "
                    Else
                        Label15.Text = "Date Open: "
                    End If

                    If txtPartNo.Text = "M705PCIS4000" Or "GY4CS000P110" And lblstatus.Text = "SMT" Then
                        Dim cnstr = mainForm.cnstr
                        Dim conn As New SqlConnection(cnstr)
                        Dim myQuery As String
                        myQuery = "SELECT * FROM PartsLog WHERE MaterialID = '" & txtSerial.Text & "' and status = 'Mounted' order by lastupdated asc"

                        Dim mycommand As SqlCommand
                        mycommand = New SqlCommand(myQuery, conn)
                        Dim spdate As Date

                        Try
                            conn.Open()
                            Dim reader As SqlDataReader = mycommand.ExecuteReader()
                            reader.Read()
                            Dim NextTime As Date
                            NextTime = NextTime.AddDays(2)
                            spdid.Text = reader("MaterialID")
                            splotno.Text = reader("LotNo")
                            lbldo.Text = reader("lastupdated")
                            conn.Close()
                            spdate = lbldo.Text
                            lbled.Text = spdate.AddDays(2)

                            If lbled.Text <= Date.Now Then
                                proceed = True
                                NotificationForm.text = "48 HOURS EXPIRED SOLDER PASTE"
                                NotificationForm.ShowDialog()

                            Else
                                proceed = False
                            End If
                        Catch ex As Exception
                            'MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
                        End Try
                        conn.Close()

                    ElseIf txtPartNo.Text = "M705PCIS4000" Or "GY4CS000P110" And lblstatus.Text = "PDN" Then

                        Dim cnstr = mainForm.cnstr
                        Dim conn As New SqlConnection(cnstr)
                        Dim myQuery As String
                        myQuery = "SELECT * FROM PartsLog WHERE MaterialID = '" & txtSerial.Text & "' and status = 'Issued' order by lastupdated asc"

                        Dim mycommand As SqlCommand
                        mycommand = New SqlCommand(myQuery, conn)
                        Dim spdate As Date

                        Try
                            conn.Open()
                            Dim reader As SqlDataReader = mycommand.ExecuteReader()
                            reader.Read()
                            Dim NextTime As Date
                            NextTime = NextTime.AddDays(3)
                            spdid.Text = reader("MaterialID")
                            splotno.Text = reader("LotNo")
                            lbldo.Text = reader("lastupdated")
                            conn.Close()
                            spdate = lbldo.Text
                            lbled.Text = spdate.AddDays(3)

                            If lbled.Text <= Date.Now Then
                                proceed = True
                                NotificationForm.text = "72 HOURS EXPIRED SOLDER PASTE"
                                NotificationForm.ShowDialog()

                            Else
                                proceed = False
                            End If
                        Catch ex As Exception
                            'MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
                        End Try
                        conn.Close()

                    Else
                        proceed = False

                    End If

                End If
            End If

            If proceed = False Then
                'validate inputs

                If validateInput() Then
                    str = Split(txtFeeder.Text, "-")

                    Dim mounting As New Mounting

                    mounting.mDate = DateTime.Now
                    mounting.machine = str(0)
                    mounting.revision = sequence.revision
                    mounting.feeder = str(1)
                    mounting.partno = txtPartNo.Text
                    mounting.quantity = CDbl(txtQuantity.Text)
                    mounting.lotNumber = txtLotNum.Text
                    mounting.mOperator = txtOperator.Text
                    mounting.lblserial = txtSerial.Text
                    mounting.sequenceno = kseqno
                    mounting.threePL = 0
                    sequence.sequenceno = kseqno

                    If sequence.verify(txtPartNo.Text, str(0), str(1)) = True Then

                        If reload Then

                            If match Then

                                lbl_Pass.Visible = True
                                lbl_fail.Visible = False
                                lblMatch.Visible = False
                                mounting.verify = 1
                                status = True
                                mountAfter = True
                                Timer1.Enabled = True
                                updateDGPass(txtFeeder.Text)

                                Dim parts As New PartsRecords
                                parts.mount(txtSerial.Text)
                            Else
                                UpdateComPort()
                                SerialPort1.Open()
                                SerialPort1.Write("B")
                                SerialPort1.Close()
                                lblMatch.Visible = True
                                lbl_Pass.Visible = False
                                lbl_fail.Visible = True
                                Timer1.Enabled = True
                                status = False
                                match = False
                                failverification.Show()
                                Me.Enabled = False
                            End If
                        Else

                            lbl_Pass.Visible = True
                            lbl_fail.Visible = False
                            lblMatch.Visible = False
                            mounting.verify = 1
                            status = True
                            mountAfter = True
                            Timer1.Enabled = True
                            updateDGPass(txtFeeder.Text)

                            If loginForm.userType = "Operator" Then
                                If Not isQA Then
                                    Dim parts As New PartsRecords
                                    parts.mount(txtSerial.Text)
                                End If
                            Else
                                'mounting.add_hist(reload, qacheck, status)
                            End If
                        End If

                    Else

                        If reload Then
                            If match Then
                                UpdateComPort()
                                SerialPort1.Open()
                                SerialPort1.Write("B")
                                SerialPort1.Close()
                                lbl_Pass.Visible = False
                                lbl_fail.Visible = True
                                lblMatch.Visible = False
                                mounting.verify = 0
                                status = False
                                mountAfter = True
                                Timer1.Enabled = True
                                updateDGFail(txtFeeder.Text)
                                failverification.Show()
                                Me.Enabled = False

                            Else

                                lblMatch.Visible = True
                                lbl_Pass.Visible = False
                                lbl_fail.Visible = False
                                mounting.verify = 0
                                status = False
                                mountAfter = True
                                Timer1.Enabled = True
                                updateDGFail(txtFeeder.Text)

                                If (Me.mismatch) Then
                                    UpdateComPort()
                                    SerialPort1.Open()
                                    SerialPort1.Write("B")
                                    SerialPort1.Close()
                                    NotificationForm.text = "New and Old Part Number Mismatch!"
                                    NotificationForm.ShowDialog()
                                    Me.mismatch = False
                                    failverification.Show()
                                    Me.Enabled = False

                                End If

                            End If
                        Else
                            
                            lbl_Pass.Visible = False
                            lbl_fail.Visible = True
                            lblMatch.Visible = False
                            mounting.verify = 0
                            status = False
                            mountAfter = True
                            Timer1.Enabled = True
                            updateDGFail(txtFeeder.Text)
                            failverification.Show()

                            'UpdateComPort()
                            'SerialPort1.Open()
                            'SerialPort1.Write("A")
                            'SerialPort1.Close()
                        End If
                    End If

                    mounting.add(mounted, isQA, status)



                    checkComplete()
                Else
                    If (Me.notissued) Then
                        UpdateComPort()
                        SerialPort1.Open()
                        SerialPort1.Write("B")
                        SerialPort1.Close()
                        NotificationForm.text = "Parts not issued!"
                        NotificationForm.ShowDialog()
                        Me.notissued = False
                        failverification.Show()
                    End If
                    If (Me.wrongline) Then
                        UpdateComPort()
                        SerialPort1.Open()
                        SerialPort1.Write("A")
                        SerialPort1.Close()
                        NotificationForm.text = "Wrong line!"
                        NotificationForm.ShowDialog()
                        Me.wrongline = False
                        failverification.Show()
                    End If
                    txtStart.Text = String.Empty
                    txtStart.Focus()

                End If
            End If
        End If
    End Sub

    Public Shared Function IsNumeric(ByVal sText As String) As Boolean
        If Double.TryParse(sText, Globalization.NumberStyles.AllowDecimalPoint) Then
            Return True
        Else
            Return False
        End If
    End Function

    Public Shared Function IsSerialNumber(ByVal sText As String, ByVal isVerification As Boolean, ByVal line As String) As Boolean
        Dim isPartNo As Boolean = False
        Dim cnstr = mainForm.cnstr
        Dim conn As New SqlConnection(cnstr)
        Dim myQuery As String

        If sText.StartsWith("LA") Then
            'Dim myQuery As String
            myQuery = "SELECT * FROM [Toshiba_kanban].[dbo].[PartsRecords] WHERE SerialNum = '" & sText & "' AND (Status = 'PDN' OR Status = 'SMT') "
            '(SELECT TOP 1 line FROM [dbo].[PartsPrepLog] WHERE status = 'Issuance' and lot_no = '" & sText & "' order by lastupdate desc) = '" & line & "'"
            'myQuery = "SELECT * FROM PartsRecords WHERE SerialNum = '" & sText & "' AND (Status = 'PDN' OR Status = 'SMT') AND (SELECT TOP 1 line FROM [dbo].[PartsPrepLog] WHERE status = 'Issuance' and lot_no = '" & sText & "' order by lastupdate desc) = '" & line & "'"
        Else
            'Dim myQuery As String
            myQuery = "SELECT * FROM [Toshiba_kanban].[dbo].[PartsRecords] WHERE SerialNum = '" & sText.Substring(0, 10) & "' AND (Status = 'PDN' OR Status = 'SMT') "
            '(SELECT TOP 1 line FROM [dbo].[PartsPrepLog] WHERE status = 'Issuance' and lot_no = '" & sText.Substring(0, 10) & "' order by lastupdate desc) = '" & line & "'
            'myQuery = "SELECT * FROM PartsRecords WHERE SerialNum = '" & sText.Substring(0, 10) & "' AND (Status = 'PDN' OR Status = 'SMT') AND (SELECT TOP 1 line FROM [dbo].[PartsPrepLog] WHERE status = 'Issuance' and lot_no = '" & sText.Substring(0, 10) & "' order by lastupdate desc) = '" & line & "'"
        End If


        Dim mycommand As SqlCommand
        mycommand = New SqlCommand(myQuery, conn)

        Try
            conn.Open()
            Dim reader As SqlDataReader = mycommand.ExecuteReader()
            If reader.HasRows Then
                reader.Read()

                Dim status = reader("Status").ToString
                If sText.StartsWith("LA") Then
                    myQuery = "SELECT TOP 1 line FROM [dbo].[PartsPrepLog] WHERE status = 'Issuance' and lot_no = '" & sText & "' order by lastupdate desc"
                Else
                    myQuery = "SELECT TOP 1 line FROM [dbo].[PartsPrepLog] WHERE status = 'Issuance' and lot_no = '" & sText.Substring(0, 10) & "' order by lastupdate desc"
                End If

                reader.Close()

                mycommand = New SqlCommand(myQuery, conn)
                reader = mycommand.ExecuteReader()

                reader.Read()

                If (reader("line") = line) Then
                    If (isVerification) Then
                        If (status = "SMT") Then
                            mountingForm.mounted = True
                            isPartNo = True
                        Else
                            mountingForm.mounted = False
                            isPartNo = False
                        End If
                    Else
                        If (status = "SMT") Then
                            mountingForm.mounted = True
                        Else
                            mountingForm.mounted = False
                        End If

                        isPartNo = True
                    End If
                Else

                    isPartNo = False
                    mountingForm.wrongline = True
                End If


            Else
                isPartNo = False
                mountingForm.notissued = True
            End If
            reader.Close()
            conn.Close()
        Catch ex As Exception
            MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
            conn.Close()
        End Try
        Return isPartNo
    End Function

    Public Shared Function getDesc(ByVal partNum As String) As String
        Dim desc As String = String.Empty

        Dim cnstr = mainForm.cnstr
        Dim conn As New SqlConnection(cnstr)

        Dim myQuery As String
        myQuery = "SELECT * FROM KPARTS WHERE KPTPARTNUM = '" & partNum & "'"

        Dim mycommand As SqlCommand
        mycommand = New SqlCommand(myQuery, conn)

        Try
            conn.Open()
            Dim reader As SqlDataReader = mycommand.ExecuteReader()
            reader.Read()
            desc = reader("KPTDESCRIPTION")
            conn.Close()
        Catch ex As Exception
            MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
            conn.Close()
        End Try

        Return desc
    End Function

    Private Function validateInput() As Boolean
        Dim valid As Boolean = False

        If qacheck = True Then
            If txtPartNo.Text <> "" And txtFeeder.Text <> "" And txtOperator.Text <> "" Then
                valid = True
            End If
        Else
            If txtPartNo.Text <> "" And txtFeeder.Text <> "" And txtLotNum.Text <> "" And txtQuantity.Text <> "" And txtOperator.Text <> "" Then
                valid = True
            End If
        End If

        Return valid
    End Function

    Private Sub clear()
        txtSerial.Text = String.Empty
        txtFeeder.Text = String.Empty
        txtPartNo.Text = String.Empty
        txtPartDesc.Text = String.Empty
        txtQuantity.Text = String.Empty
        txtLotNum.Text = String.Empty
        txtOperator.Text = String.Empty
        txtStart.Text = String.Empty
    End Sub

    Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
        If Timer1.Enabled = True Then
            If Timer1.Tag = True Then
                If match = True Then
                    If status = True Then
                        lbl_Pass.Visible = True
                    Else
                        lbl_fail.Visible = True
                    End If
                Else
                    lblMatch.Visible = True
                End If
                Timer1.Tag = False
            Else
                If match = True Then
                    If status = True Then
                        lbl_Pass.Visible = False
                    Else
                        lbl_fail.Visible = False
                    End If
                Else
                    lblMatch.Visible = False
                End If
                Timer1.Tag = True
            End If
        End If
    End Sub

    Private Sub btn_setSequence_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btn_setSequence.Click


        If mountStart = False Then
            If cmbSeq.SelectedItem <> "" And cmbRev.SelectedItem <> "" And cmbModel.SelectedItem <> "" And cmbLine.SelectedItem <> "" And cmbType.SelectedItem <> "" Then
                kseqno = sequence.getSequenceNo(cmbSeq.SelectedItem, cmbLine.SelectedItem, cmbModel.SelectedItem, cmbType.SelectedItem, cmbRev.SelectedItem)
                'MsgBox(kseqno)
                sequence.account = cmbSeq.SelectedItem
                sequence.revision = cmbRev.SelectedItem

                Dim m As New Mounting
                m.addSettings(cmbLine.SelectedItem.ToString, kseqno)
                cmbSeq.Enabled = False
                cmbRev.Enabled = False
                cmbModel.Enabled = False
                cmbLine.Enabled = False
                cmbType.Enabled = False
                btn_reload.Enabled = True
                btn_Check.Enabled = True

                If isQA Then
                    btnReload.Visible = True
                Else
                    btnQA.Visible = True
                End If
                btn_setSequence.Text = "Change Sequence"
                txtStart.Focus()

                'If (Not currentsequence = sequence.account Or Not currentrev = sequence.revision Or Not currentmodel = sequence.model Or Not currentline = sequence.line Or Not currenttype = sequence.pcbside) Then
                '    qaMode()
                '    clear()
                '    Timer1.Stop()
                '    lbl_fail.Visible = False
                '    lbl_Pass.Visible = False
                '    btnReload.Visible = False
                'Else 
                '    checkComplete()
                'End If

                If (MessageBox.Show("Do you want to resume mounting sequence?", "Message", MessageBoxButtons.YesNo, MessageBoxIcon.Question) = Windows.Forms.DialogResult.Yes) Then
                    checkComplete()
                    reloadMode()
                    reload = True
                    verificationTime = DateTime.Now.AddHours(2)
                    'verificationTime = DateTime.Now.AddMinutes(1)
                    lblVerification.Text = "Next Verification: " & verificationTime.ToString
                    checkVerification = True
                    Timer2.Start()
                Else
                    qaMode()
                    clear()
                    Timer1.Stop()
                    Timer2.Stop()
                    checkVerification = False
                    lbl_fail.Visible = False
                    lbl_Pass.Visible = False
                    lblMatch.Visible = False
                    btnReload.Visible = False

                End If

                currentsequence = sequence.account
                currentrev = sequence.revision
                currentline = sequence.line
                currentmodel = sequence.model
                currenttype = sequence.pcbside
                mountStart = True

            Else
                MessageBox.Show("Please select the machine and revision to use.", "Set Machine", MessageBoxButtons.OK, MessageBoxIcon.Error)
            End If

        Else

            btn_setSequence.Text = "Set Sequence"
            btnQA.Visible = False
            cmbSeq.Enabled = True
            cmbRev.Enabled = True
            cmbModel.Enabled = True
            cmbLine.Enabled = True
            cmbType.Enabled = True
            btn_reload.Enabled = False
            btn_Check.Enabled = False
            btnReload.Visible = False
            mountStart = False

        End If



    End Sub

    Private Sub getExpirationDate()
        'If cmbSeq.SelectedItem <> "" And cmbRev.SelectedItem <> "" And cmbModel.SelectedItem <> "" And cmbLine.SelectedItem <> "" And cmbType.SelectedItem <> "" Then
        '    kseqno = sequence.getSequenceNo(cmbSeq.SelectedItem, cmbLine.SelectedItem, cmbModel.SelectedItem, cmbType.SelectedItem, cmbRev.SelectedItem)

        Dim cnstr = mainForm.cnstr
        Dim conn As New SqlConnection(cnstr)

        Dim myQuery As String
        myQuery = "SELECT * FROM KMOUNTING WHERE KMTPARTNO = 'M705PCIS4000' or KMTPARTNO = 'GY4CS000P110'  AND KMTMACHINE = '0" & cmbLine.Text & "' ORDER BY KMTDATE DESC"

        Dim mycommand As SqlCommand
        mycommand = New SqlCommand(myQuery, conn)
        Dim spdate As Date

        Try
            conn.Open()
            Dim reader As SqlDataReader = mycommand.ExecuteReader()
            reader.Read()
            Dim NextTime As Date
            NextTime = NextTime.AddDays(2)
            spdid.Text = reader("KMTLABEL")
            splotno.Text = reader("KMTLOT")
            lbldo.Text = reader("KMTDATE")
            conn.Close()

            spdate = lbldo.Text
            lbled.Text = spdate.AddDays(2)

            If lbled.Text <= Date.Now Then
                NotificationForm.text = "EXPIRED SOLDER PASTE"
                NotificationForm.ShowDialog()
            End If


        Catch ex As Exception
            'MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)

        End Try
        conn.Close()
        'End If

    End Sub

    Private Sub cmbSeq_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmbSeq.SelectedIndexChanged
        getLines()

        btn_reload.Enabled = False
        btn_Check.Enabled = False

    End Sub

    Private Sub btn_reload_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btn_reload.Click

        If reload = False Then

            btn_reload.Text = "Set Normal Mode"
            reload = True
            btn_Check.Visible = False
            txtStart.Focus()
            Me.BackColor = Color.HotPink

        Else

            btn_reload.Text = "Set Reload Mode"
            reload = False
            btn_Check.Visible = False
            txtStart.Focus()
            Me.BackColor = System.Drawing.SystemColors.Control

        End If
    End Sub

    Private Sub GroupBox1_Enter(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles GroupBox1.Enter

    End Sub

    Public Sub qaMode()

        btnReload.Text = "Normal Mode"
        btnComplete.Visible = True
        qacheck = True
        btnQA.Visible = False
        btnReload.Visible = False
        btn_reload.Visible = False
        txtLotNum.Visible = False
        Label8.Visible = False
        txtQuantity.Visible = False
        Label7.Visible = False
        If isVerification Then
            Me.BackColor = Color.PaleVioletRed
        Else
            Me.BackColor = Color.Goldenrod
        End If
        dg.Visible = True
        fillDataSet()
        fillDataGridView()
        txtStart.Focus()
        UpdateComPort()

    End Sub

    Private Sub btn_Check_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btn_Check.Click

        If qacheck = False Then
            qaMode()
        Else
            reloadMode()
        End If

    End Sub

    Public Sub reloadMode()
        btnReload.Text = "Normal Mode"
        btnComplete.Visible = False
        btnQA.Visible = True
        btnReload.Visible = False
        reload = True
        qacheck = False
        btn_reload.Visible = False
        txtLotNum.Visible = True
        Label8.Visible = True
        txtQuantity.Visible = True
        Label7.Visible = True
        Me.BackColor = System.Drawing.SystemColors.Control
        dg.Visible = False
        txtStart.Focus()
    End Sub


    Private Sub initializeDG()

        Dim Serial As New DataGridViewTextBoxColumn
        Dim Feeder As New DataGridViewTextBoxColumn
        Dim PartNo As New DataGridViewTextBoxColumn
        Dim Status As New DataGridViewTextBoxColumn


        Serial.HeaderText = "Serial"
        Feeder.HeaderText = "Feeder"
        PartNo.HeaderText = "PartNumber"
        Status.HeaderText = "Status"



        dg.Columns.Add(Feeder)
        dg.Columns.Add(PartNo)
        dg.Columns.Add(Status)
        dg.Columns.Add(Serial)

        dg.Columns(0).ReadOnly = True
        dg.Columns(1).ReadOnly = True
        dg.Columns(2).ReadOnly = True
        dg.Columns(3).ReadOnly = True

        dg.AutoSizeColumnsMode = DataGridViewAutoSizeColumnMode.None

        dg.Columns(0).Width = 75
        dg.Columns(1).Width = 180
        dg.Columns(2).Width = 100
        dg.Columns(3).Width = 150



        dg.Columns(0).SortMode = DataGridViewColumnSortMode.Programmatic
        dg.Columns(1).SortMode = DataGridViewColumnSortMode.Programmatic
        dg.Columns(2).SortMode = DataGridViewColumnSortMode.Programmatic
        dg.Columns(3).SortMode = DataGridViewColumnSortMode.Programmatic

    End Sub

    Private Sub fillDataSet()
        Dim i As Integer
        Dim limit As Integer
        Dim cnstr = mainForm.cnstr
        Dim conn As New SqlConnection(cnstr)
        Dim adapter As New SqlDataAdapter
        kseqno = sequence.getSequenceNo(cmbSeq.SelectedItem, cmbLine.SelectedItem, cmbModel.SelectedItem, cmbType.SelectedItem, cmbRev.SelectedItem)
        Dim myQuery As String
        myQuery = "SELECT * FROM KSEQUENCE_DETAIL WHERE KSEQUENCENO = '" & kseqno & "'"

        Dim mycommand As SqlCommand
        mycommand = New SqlCommand(myQuery, conn)

        Try
            conn.Open()
            adapter.SelectCommand = mycommand
            ds.Clear()
            adapter.Fill(ds)
            i = 0
            limit = ds.Tables(0).Rows.Count - 1

        Catch ex As Exception
            MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
        Finally
            conn.Close()
        End Try
    End Sub

    Private Sub fillDataGridView()
        Dim i As Integer = 0

        dg.Rows.Clear()
        For i = 0 To ds.Tables(0).Rows.Count - 1
            dg.Rows.Add()
            dg.Rows(i).Cells(0).Value = ds.Tables(0).Rows(i).Item("KSQMODULE") + "-" + ds.Tables(0).Rows(i).Item("KSQFEEDERNO")
            dg.Rows(i).Cells(1).Value = ds.Tables(0).Rows(i).Item("KSQPARTNO")
            dg.Rows(i).Cells(2).Value = ""
            dg.Rows(i).Cells(3).Value = ""
        Next
    End Sub


    Private Sub updateDGPass(ByVal Feeder As String)

        Dim i As Integer = 0

        If dg.Rows.Count > 0 Then
            While i < dg.Rows.Count
                If dg.Rows(i).Cells(0).Value = Feeder Then
                    dg.Rows(i).Cells(2).Value = "PASS"
                    dg.Rows(i).Cells(3).Value = txtSerial.Text

                    dg.Rows(i).Cells(0).Style.BackColor = Color.Green
                    dg.Rows(i).Cells(1).Style.BackColor = Color.Green
                    dg.Rows(i).Cells(2).Style.BackColor = Color.Green
                    dg.Rows(i).Cells(3).Style.BackColor = Color.Green

                    'dg.Rows(i).Selected = True
                    'dg.Rows(i).Cells(0).Selected = True
                    dg.CurrentCell = dg(0, i)

                End If
                i = i + 1
            End While
        End If

    End Sub

    Private Sub updateDGFail(ByVal Feeder As String)

       

        Dim i As Integer = 0

        If dg.Rows.Count > 0 Then
            While i < dg.Rows.Count
                If dg.Rows(i).Cells(0).Value = Feeder Then
                    dg.Rows(i).Cells(2).Value = "FAIL"
                    dg.Rows(i).Cells(3).Value = txtSerial.Text

                    dg.Rows(i).Cells(0).Style.BackColor = Color.Red
                    dg.Rows(i).Cells(1).Style.BackColor = Color.Red
                    dg.Rows(i).Cells(2).Style.BackColor = Color.Red
                    dg.Rows(i).Cells(3).Style.BackColor = Color.Red

                    'dg.Rows(i).Selected = True
                    'dg.Rows(i).Cells(0).Selected = True
                    dg.CurrentCell = dg(0, i)


                End If
                i = i + 1
            End While
           

        End If


    End Sub

    Private Sub btnComplete_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnComplete.Click

        Dim msg As String = ""
        Dim i As Integer = 0
        Dim t As Integer = 0
        Dim p As Integer = 0
        Dim f As Integer = 0

        If dg.Rows.Count > 0 Then
            While i < dg.Rows.Count - 1
                If dg.Rows(i).Cells(2).Value <> "" Then
                    If dg.Rows(i).Cells(2).Value = "PASS" Then
                        p = p + 1
                    End If
                    If dg.Rows(i).Cells(2).Value = "FAIL" Then
                        f = f + 1
                    End If
                    t = t + 1
                End If
                i = i + 1
            End While
        End If

        msg = vbCrLf + "RESULT :" + vbCrLf + t.ToString + "   of   " + i.ToString + "  checked" + vbCrLf + vbCrLf + "PASSED = " + p.ToString + vbCrLf + "FAILED = " + f.ToString
        myMessageBox.Show(msg)
        txtStart.Focus()

    End Sub


    Private Sub checkComplete()

        Dim i As Integer = 0
        Dim t As Integer = 0


        If dg.Rows.Count > 0 Then
            While i < dg.Rows.Count - 1
                If dg.Rows(i).Cells(2).Value <> "" Then
                    t = t + 1
                End If
                i = i + 1
            End While
        End If

        If i = t Then
            'If btnComplete.Visible = False Then
            'btnComplete_Click(Me, EventArgs.Empty)
            ' End If

            If qacheck Then
                btnComplete_Click(Me, EventArgs.Empty)
                Dim p As Integer = 0
                Dim f As Integer = 0
                i = 0
                t = 0
                If dg.Rows.Count > 0 Then
                    While i < dg.Rows.Count - 1
                        If dg.Rows(i).Cells(2).Value <> "" Then
                            If dg.Rows(i).Cells(2).Value = "PASS" Then
                                p = p + 1
                            End If
                            If dg.Rows(i).Cells(2).Value = "FAIL" Then
                                f = f + 1
                            End If
                            t = t + 1
                        End If
                        i = i + 1
                    End While
                End If

                If f = 0 Then
                    If isVerification Then
                        Dim name = InputBox("Enter QA username", "QA Verification", "")
                        Do While (name = "" Or (name <> "032712FERNAN" And name <> "033740ERWIN" And name <> "034356REA" And name <> "034412JUDY" And name <> "034532LYN" And name <> "034423AYAH" And name <> "032604ANA" And name <> "032766GHIE" And name <> "032703JACKIE"))
                            name = InputBox("Enter QA username", "QA Verification", "")
                        Loop
                        isVerification = False

                    End If
                    MsgBox("Complete!", MsgBoxStyle.OkOnly)

                    clear()
                    reloadMode()
                    reload = True

                End If
            Else

                clear()
                reloadMode()
                reload = True
            End If
        End If

    End Sub


    Private Sub dg_CellContentClick(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles dg.CellContentClick
        txtStart.Focus()
    End Sub

    Private Sub dg_CellClick(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles dg.CellClick
        txtStart.Focus()
    End Sub

    Private Sub dg_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles dg.Click
        txtStart.Focus()
    End Sub


    Private Sub cmbPlant_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs)
        getSequence()
    End Sub

    Private Sub chkstart_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles chkstart.CheckedChanged
        If chkstart.Checked = True Then
            fillDataSet()
            fillDataGridView()
            txtStart.Focus()
        Else

        End If
    End Sub

    Private Sub btnReload_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnReload.Click
        'qacheck = False
        isQA = False
        reload = True
        reloadMode()
        clear()
    End Sub

    Private Sub btnQA_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnQA.Click
        isQA = True
        reload = False
        isVerification = True
        qaMode()
        clear()
        btnReload.Visible = True
    End Sub

    Private Sub cmbLine_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmbLine.SelectedIndexChanged



        SerialPort1.Close()
        SerialPort1.PortName = getPort(cmbLine.Text).ToString
        'SerialPort1.PortName = "COM3"
        SerialPort1.BaudRate = 9600
        SerialPort1.DataBits = 8
        SerialPort1.Parity = Parity.None
        SerialPort1.StopBits = StopBits.One
        SerialPort1.Handshake = Handshake.None
        SerialPort1.Encoding = System.Text.Encoding.Default
        ComportTextBox.Text = getPort(cmbLine.Text).ToString
        'failverification.ComportLabel.Text = getPort(cmbLine.Text).ToString
        getModels()

    End Sub
    Private Sub UpdateComPort()
        SerialPort1.Close()
        SerialPort1.PortName = getPort(cmbLine.Text).ToString
        'SerialPort1.PortName = "COM3"
        SerialPort1.BaudRate = 9600
        SerialPort1.DataBits = 8
        SerialPort1.Parity = Parity.None
        SerialPort1.StopBits = StopBits.One
        SerialPort1.Handshake = Handshake.None
        SerialPort1.Encoding = System.Text.Encoding.Default
    End Sub
    Private Sub cmbModel_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmbModel.SelectedIndexChanged
        getTypes()
    End Sub

    Private Sub cmbType_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmbType.SelectedIndexChanged
        getRevisions()
    End Sub

    Private Sub Button1_Click_1(sender As System.Object, e As System.EventArgs) Handles Button1.Click
        sequential.Show()
    End Sub

    Public Function getPort(ByVal line As String)
        Dim PortLine As String = ""
        Dim cnstr = mainForm.cnstr
        Dim conn As New SqlConnection(cnstr)

        Dim myQuery As String
        myQuery = "SELECT KPortnum FROM KPORT " & _
                  "WHERE KLine = '" & line & "' " 
        Dim mycommand As SqlCommand
        mycommand = New SqlCommand(myQuery, conn)

        Try
            conn.Open()
            Dim reader As SqlDataReader = mycommand.ExecuteReader()
            If reader.HasRows Then
                reader.Read()
                PortLine = reader("KPortnum")
            End If
            conn.Close()
        Catch ex As Exception
            MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
            conn.Close()
        End Try
        Return PortLine
    End Function


    Private Sub lblVerification_Click(sender As System.Object, e As System.EventArgs) Handles lblVerification.Click

    End Sub

    Private Sub Timer3_Tick(sender As System.Object, e As System.EventArgs) Handles Timer3.Tick

        Dim cnstr = mainForm.cnstr
        Dim conn As New SqlConnection(cnstr)
        Dim stime As String = ""
        Dim myQuery As String
        myQuery = "SELECT GETDATE() AS SERVERTIME "
        Dim mycommand As SqlCommand
        mycommand = New SqlCommand(myQuery, conn)


        Try
            conn.Open()
            Dim reader As SqlDataReader = mycommand.ExecuteReader()
            If reader.HasRows Then
                reader.Read()
                stime = reader("SERVERTIME")
            End If
            conn.Close()
        Catch ex As Exception
            MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
            conn.Close()
        End Try

        Dim mydate As DateTime = stime
        Dim hour As Integer = mydate.Hour
        Dim min As Integer = mydate.Minute


        If (hour = 2 And min = 30) Then
            Me.Enabled = False
            sequential.Show()
            Timer3.Stop()
        ElseIf (hour = 4 And min = 30) Then
            Me.Enabled = False
            sequential.Show()
            Timer3.Stop()
        ElseIf (hour = 6 And min = 30) Then
            Me.Enabled = False
            sequential.Show()
            Timer3.Stop()
        ElseIf (hour = 8 And min = 30) Then
            Me.Enabled = False
            sequential.Show()
            Timer3.Stop()
        ElseIf (hour = 10 And min = 30) Then
            Me.Enabled = False
            sequential.Show()
            Timer3.Stop()
        ElseIf (hour = 12 And min = 30) Then
            Me.Enabled = False
            sequential.Show()
            Timer3.Stop()
        ElseIf (hour = 14 And min = 30) Then
            Me.Enabled = False
            sequential.Show()
            Timer3.Stop()
        ElseIf (hour = 16 And min = 30) Then
            Me.Enabled = False
            sequential.Show()
            Timer3.Stop()
        ElseIf (hour = 18 And min = 30) Then
            Me.Enabled = False
            sequential.Show()
            Timer3.Stop()
        ElseIf (hour = 20 And min = 30) Then
            Me.Enabled = False
            sequential.Show()
            Timer3.Stop()
        ElseIf (hour = 22 And min = 30) Then
            Me.Enabled = False
            sequential.Show()
            Timer3.Stop()
        ElseIf (hour = 24 And min = 30) Then
            Me.Enabled = False
            sequential.Show()
            Timer3.Stop()

        End If
    End Sub



End Class