Imports System.Data.SqlClient
Imports Logic.DateExtensions
Imports Logic.NullableDateExtensions
Imports Logic.NullableDoubleExtensions
Imports ReportingClass

Public Class EducationInfo
    Inherits System.Web.UI.Page

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

            If Not Page.IsPostBack Then
                If Not _HasVisited() Then
                    _Prefill()
                End If
                _LoadForm()
                _LoadLists()
            Else
                _SaveAll()
                Page.Validate()
                If Page.IsValid Then
                    Master.EnableNextPage()
                End If
            End If

        Catch ex As Exception
            Dim errorId = Logic.Error.Log(ex)
            Response.Redirect("/Error.aspx?id=" & errorId)
        End Try
    End Sub


    Private Sub btnAddSchool_Click(sender As Object, e As EventArgs) Handles rptSchools.AddClick
        Try
            If _HasEnteredLastSchool() Then
                rptSchools.TargetCount = Math.Max(rptSchools.TargetCount, rptSchools.Items.Count) + 1
            End If
            _LoadSchoolList()
        Catch ex As Exception
            Dim errorId = Logic.Error.Log(ex)
            Response.Redirect("/Error.aspx?id=" & errorId)
        End Try
    End Sub

    Public Sub btnRemoveSchool_Click(sender As Object, e As EventArgs)
        Try

            rptSchools.TargetCount = Math.Max(rptSchools.TargetCount, rptSchools.Items.Count) - 1

            Dim btnRemove = DirectCast(sender, Button)
            Dim item = DirectCast(btnRemove.Parent, RepeaterItem)
            Dim hidId = DirectCast(item.FindControl("hidSchoolId"), HiddenField)

            _RemoveSchool(CInt(hidId.Value))
            _LoadSchoolList()

        Catch ex As Exception
            Dim errorId = Logic.Error.Log(ex)
            Response.Redirect("/Error.aspx?id=" & errorId)
        End Try
    End Sub


#Region "Loading internals"

    Private Sub _LoadForm()
        Using connection As New SqlConnection(Logic.Database.ConnectionString)
            connection.Open()

            Dim cmd As New SqlCommand("
                SELECT
                    -- driver info
                    applicantNameFirst, applicantNameMiddle, applicantNameLast, applicantNameSuffix, 
                    applicantSocial, applicantDob, applicantAddress, applicantAddress2,
                    applicantCity, applicantState, applicantZip, applicantPhone, applicantEmail,
                    -- General info
                    desiredPosition, desiredSchedule, desiredPay, desiredPaySchedule, referredBy,
                    isFormerEmployee, formerEmployeeFrom, formerEmployeeTo, formerEmployeeLocation, 
                    formerLocationPosition, formerEmployeePay, formerEmployeePaySchedule, formerEmployeeReasonLeft, 
                    relativesEmployed, isCurrentlyEmployed, timeSinceEmployment, 
                    legallyEmployable, isFelon, felonExplanation, hasLivedAtAddress3Years
                FROM web_DriverApplication WHERE id=@appId",
                connection)
            cmd.Parameters.AddWithValue("appId", Master.app.id)
            Dim dReader = cmd.ExecuteReader()
            dReader.Read()


        End Using
    End Sub

    Private Sub _LoadLists()
        _LoadSchoolList()
    End Sub



    Private Sub _LoadSchoolList()
        Using connection As New SqlConnection(Logic.Database.ConnectionString)
            connection.Open()

            Dim cmdCount As New SqlCommand(
                "SELECT COUNT(id) FROM web_DriverApplicationSchools WHERE AppId=@appId",
                connection)
            cmdCount.Parameters.AddWithValue("appId", Master.app.id)
            Dim count = CInt(cmdCount.ExecuteScalar())
            count = Math.Max(count, rptSchools.TargetCount)

            Dim cmdSchools As New SqlCommand("
                SELECT * FROM web_DriverApplicationSchools
                WHERE AppId=@appId",
                connection)
            cmdSchools.Parameters.AddWithValue("appId", Master.app.id)

            Dim dummy As New List(Of Integer)
            For i = 1 To count : dummy.Add(i) : Next
            rptSchools.DataSource = dummy
            rptSchools.DataBind()

            ' We lose list of states after repeater rebind.
            ' This refills the states so that we can set them back.
            For Each item As RepeaterItem In rptSchools.Items
                Dim ddlState As StatePicker = item.FindControl("ddlSchoolState")
                ddlState.Rebind()
            Next

            Dim dReader = cmdSchools.ExecuteReader()
            For Each item As RepeaterItem In rptSchools.Items
                Dim hidId As HiddenField = item.FindControl("hidSchoolId")
                Dim ddlSchoolType As DropDownList = item.FindControl("ddlSchoolType")
                Dim txtSchoolName As TextBox = item.FindControl("txtSchoolName")
                Dim txtSchoolCity As TextBox = item.FindControl("txtSchoolCity")
                Dim ddlSchoolState As StatePicker = item.FindControl("ddlSchoolState")
                Dim txtSchoolHighestLevel As TextBox = item.FindControl("txtSchoolHighestLevel")

                If dReader.Read() Then
                    hidId.Value = dReader("id")
                    ddlSchoolType.SelectedValue = dReader("Type")
                    txtSchoolName.Text = dReader("Name")
                    txtSchoolCity.Text = dReader("City")
                    ddlSchoolState.SelectedValue = dReader("State")
                    txtSchoolHighestLevel.Text = dReader("HighestLevel")
                End If
            Next

        End Using
    End Sub

    Private Sub _Prefill()
        Using connection As New SqlConnection(Logic.Database.ConnectionString)
            connection.Open()
            Dim cmd As New SqlCommand("
                UPDATE web_DriverApplication
                SET applicantNameFirst = @nameFirst,
                    applicantNameMiddle = @nameMiddle,
                    applicantNameLast = @nameLast,
                    applicantNameSuffix = @nameSuffix,
                    applicantSocial = @social,
                    applicantPhone = @phone,
                    applicantEmail = @email
                WHERE id=@appId",
                connection)
            cmd.Parameters.AddWithValue("appId", Master.app.id)
            cmd.Parameters.AddWithValue("nameFirst", Master.Master.CurrentDriver.nameFirst)
            cmd.Parameters.AddWithValue("nameMiddle", Master.Master.CurrentDriver.nameMiddle)
            cmd.Parameters.AddWithValue("nameLast", Master.Master.CurrentDriver.nameLast)
            cmd.Parameters.AddWithValue("nameSuffix", Master.Master.CurrentDriver.nameSuffix)
            cmd.Parameters.AddWithValue("social", Master.Master.CurrentDriver.social)
            cmd.Parameters.AddWithValue("phone", Master.Master.CurrentDriver.phone)
            cmd.Parameters.AddWithValue("email", Master.Master.CurrentDriver.email)
            cmd.ExecuteNonQuery()
        End Using
    End Sub

#End Region

#Region "Saving internals"

    Private Sub _SaveAll()
        Using connection As New SqlConnection(Logic.Database.ConnectionString)
            connection.Open()
            Using transaction = connection.BeginTransaction()
                _SaveForm(connection, transaction)
                _SaveLists(connection, transaction)
                _SaveDocument(connection, transaction)
                transaction.Commit()
            End Using
        End Using
    End Sub

    Private Sub _SaveForm(connection As SqlConnection, transaction As SqlTransaction)



        'Dim cmd As New SqlCommand("
        '    UPDATE web_DriverApplication SET
        '        -- driver info
        '        applicantNameFirst=@applicantNameFirst, applicantNameMiddle=@applicantNameMiddle, applicantNameLast=@applicantNameLast, applicantNameSuffix=@applicantNameSuffix,
        '        applicantSocial=@applicantSocial, applicantDob=@applicantDob,
        '        applicantAddress=@applicantAddress, applicantAddress2=@applicantAddress2,
        '        applicantCity=@applicantCity, applicantState=@applicantState,
        '        applicantZip=@applicantZip, applicantPhone=@applicantPhone,
        '        applicantEmail=@applicantEmail, hasLivedAtAddress3years=@address3Years,
        '        -- General info
        '        desiredPosition=@desiredPosition, desiredSchedule=@desiredSchedule, 
        '        desiredPay=@desiredPay, desiredPaySchedule=@desiredPaySchedule, referredBy=@referredBy, 
        '        isFormerEmployee=@isFormerEmployee, formerEmployeeFrom=@formerEmployeeFrom, 
        '        formerEmployeeTo=@formerEmployeeTo, formerEmployeeLocation=@formerEmployeeLocation, 
        '        formerLocationPosition=@formerLocationPosition, formerEmployeePay=@formerEmployeePay, 
        '        formerEmployeePaySchedule=@formerEmployeePaySchedule,
        '        formerEmployeeReasonLeft=@formerEmployeeReasonLeft, 
        '        relativesEmployed=@relativesEmployed, isCurrentlyEmployed=@isCurrentlyEmployed, 
        '        timeSinceEmployment=@timeSinceEmployment, legallyEmployable=@legallyEmployable, 
        '        isFelon=@isFelon, felonExplanation=@felonExplanation
        '    WHERE id=@appId",
        '    connection, transaction)

        'With cmd.Parameters
        '    .AddWithValue("appId", Master.app.id)

        '    ' driver info
        '    Dim dateBirth = Logic.Conversion.ToNullableDate(txtDateBirth.Text)
        '    .AddWithValue("applicantNameFirst", txtNameFirst.Text)
        '    .AddWithValue("applicantNameMiddle", txtNameMiddle.Text)
        '    .AddWithValue("applicantNameLast", txtNameLast.Text)
        '    .AddWithValue("applicantNameSuffix", txtNameSuffix.Text)
        '    .AddWithValue("applicantSocial", txtSocial.Value)
        '    .AddWithValue("applicantDob", If(dateBirth.HasValue, dateBirth.Value, DBNull.Value))
        '    .AddWithValue("applicantAddress", txtAddress.Text)
        '    .AddWithValue("applicantAddress2", txtAddress2.Text)
        '    .AddWithValue("applicantCity", txtCity.Text)
        '    .AddWithValue("applicantState", ddlState.SelectedValue)
        '    .AddWithValue("applicantZip", txtZip.Text)
        '    .AddWithValue("applicantPhone", txtPhone.Text)
        '    .AddWithValue("applicantEmail", txtEmail.Text)

        '    ' general info
        '    .AddWithValue("desiredPosition", txtPosition.Text)
        '    .AddWithValue("desiredSchedule", ddlSchedule.SelectedValue)
        '    .AddWithValue("desiredPay", txtPayExpected.Text)
        '    .AddWithValue("desiredPaySchedule", ddlPaySchedule.SelectedValue)
        '    .AddWithValue("referredBy", txtReferredBy.Text)
        '    .AddWithValue("isFormerEmployee", If(isFormerEmployee.HasValue, isFormerEmployee.Value, DBNull.Value))
        '    .AddWithValue("formerEmployeeFrom", If(formerEmployeeFrom.HasValue, formerEmployeeFrom.Value, DBNull.Value))
        '    .AddWithValue("formerEmployeeTo", If(formerEmployeeTo.HasValue, formerEmployeeTo.Value, DBNull.Value))
        '    .AddWithValue("formerEmployeeLocation", txtPreviousEmployeeLocation.Text)
        '    .AddWithValue("formerLocationPosition", txtPreviousEmployeePosition.Text)
        '    .AddWithValue("formerEmployeePay", txtPreviousEmployeePay.Text)
        '    .AddWithValue("formerEmployeePaySchedule", ddlPreviousEmployeePaySchedule.SelectedValue)
        '    .AddWithValue("formerEmployeeReasonLeft", txtPreviousEmployeeReasonLeft.Text)
        '    .AddWithValue("relativesEmployed", txtRelativesEmployed.Text)
        '    .AddWithValue("isCurrentlyEmployed", If(isCurrentlyEmployed.HasValue, isCurrentlyEmployed.Value, DBNull.Value))
        '    .AddWithValue("timeSinceEmployment", txtTimeSinceEmployed.Text)
        '    .AddWithValue("legallyEmployable", If(legallyEmployable.HasValue, legallyEmployable.Value, DBNull.Value))
        '    .AddWithValue("isFelon", If(isFelon.HasValue, isFelon.Value, DBNull.Value))
        '    .AddWithValue("felonExplanation", txtFelonyConvictionExplanation.Text)
        '    .AddWithValue("address3Years", If(ynCurrentAddress3Years.HasControls, ynCurrentAddress3Years.ValidateRequestMode, DBNull.Value))
        'End With

        'cmd.ExecuteNonQuery()

    End Sub

    Private Sub _SaveLists(connection As SqlConnection, transaction As SqlTransaction)
        _SaveSchoolList(connection, transaction)
    End Sub

    Private Sub _SaveSchoolList(connection As SqlConnection, transaction As SqlTransaction)

        Dim cmdDelete As New SqlCommand(
            "DELETE FROM web_DriverApplicationSchools WHERE AppId=@appId",
            connection, transaction)
        cmdDelete.Parameters.AddWithValue("appId", Master.app.id)
        cmdDelete.ExecuteNonQuery()

        Dim cmdSave As New SqlCommand("
            INSERT INTO web_DriverApplicationSchools
            (AppId, Type, Name, City, State, HighestLevel)
            VALUES (@appId, @type, @name, @city, @state, @highestLevel);
            SELECT @@IDENTITY;",
            connection, transaction)
        With cmdSave.Parameters
            .AddWithValue("appId", Master.app.id)
            .Add(New SqlParameter("type", SqlDbType.VarChar))
            .Add(New SqlParameter("name", SqlDbType.VarChar))
            .Add(New SqlParameter("city", SqlDbType.VarChar))
            .Add(New SqlParameter("state", SqlDbType.VarChar))
            .Add(New SqlParameter("highestLevel", SqlDbType.VarChar))
        End With

        For Each item As RepeaterItem In rptSchools.Items
            Dim hidId As HiddenField = item.FindControl("hidSchoolId")
            Dim ddlSchoolType As DropDownList = item.FindControl("ddlSchoolType")
            Dim txtSchoolName As TextBox = item.FindControl("txtSchoolName")
            Dim txtSchoolCity As TextBox = item.FindControl("txtSchoolCity")
            Dim ddlSchoolState As StatePicker = item.FindControl("ddlSchoolState")
            Dim txtSchoolHighestLevel As TextBox = item.FindControl("txtSchoolHighestLevel")

            cmdSave.Parameters("type").Value = ddlSchoolType.SelectedValue
            cmdSave.Parameters("name").Value = txtSchoolName.Text
            cmdSave.Parameters("city").Value = txtSchoolCity.Text
            cmdSave.Parameters("state").Value = ddlSchoolState.SelectedValue
            cmdSave.Parameters("highestLevel").Value = txtSchoolHighestLevel.Text

            hidId.Value = cmdSave.ExecuteScalar()
        Next

    End Sub

    Private Sub _SaveDocument(connection As SqlConnection, transaction As SqlTransaction)
        Dim ReportDataSet As New dsAppGeneralQuestions
        Dim ReportTableAdapter As New TransactionalAppGeneralQuestionsTableAdapter
        ReportTableAdapter.SetConnection(connection, transaction)
        ReportTableAdapter.Fill(ReportDataSet.AppGeneralQuestionsDataTable, Master.app.id)

        Using Report As New crptAppGeneralQuestions
            Report.SetDataSource(ReportDataSet)
            Dim rawData = Reporting.StreamToByteArray(Report)

            Dim cmdSave = "
                UPDATE web_DriverApplicationPdf SET pageTitle=@pageTitle, pdfData=@pdfData, pdfDataSize=@pdfDataSize
                WHERE appId=@appId AND pageFileName=@pageFileName;
                IF @@ROWCOUNT = 0 BEGIN
                    INSERT INTO web_DriverApplicationPdf (appId, pageTitle, pageFileName, pdfData, pdfDataSize)
                    VALUES (@appId, @pageTitle, @pageFileName, @pdfData, @pdfDataSize);
                END"
            Dim cmd As New SqlCommand(cmdSave, connection, transaction)
            cmd.Parameters.AddWithValue("appId", Master.app.id)
            cmd.Parameters.AddWithValue("pageTitle", Master.CurrentTitle)
            cmd.Parameters.AddWithValue("pageFileName", Master.CurrentPage)
            cmd.Parameters.AddWithValue("pdfData", rawData)
            cmd.Parameters.AddWithValue("pdfDataSize", rawData.Length)
            cmd.ExecuteNonQuery()
        End Using
    End Sub

#End Region

#Region "Other internals"

    Private Function _HasEnteredLastSchool() As Boolean
        Dim count = rptSchools.Items.Count
        If count = 0 Then
            Return True
        Else
            Dim item As RepeaterItem = rptSchools.Items(count - 1)
            Dim txtSchoolName As TextBox = item.FindControl("txtSchoolName")
            Return txtSchoolName.Text.Length > 0
        End If
    End Function

    Private Function _HasVisited() As Boolean
        Using connection As New SqlConnection(Logic.Database.ConnectionString)
            connection.Open()
            Dim cmd As New SqlCommand(
                "SELECT applicantNameFirst FROM web_DriverApplication WHERE id=@appId",
                connection)
            cmd.Parameters.AddWithValue("appId", Master.app.id)
            Return TypeOf cmd.ExecuteScalar() IsNot DBNull
        End Using
    End Function

    Private Sub _RemoveAddress(itemId As Integer)
        Using connection As New SqlConnection(Logic.Database.ConnectionString)
            connection.Open()
            Dim cmd As New SqlCommand(
                "DELETE FROM web_DriverApplicationAddresses WHERE id=@itemId",
                connection)
            cmd.Parameters.AddWithValue("itemId", itemId)
            cmd.ExecuteNonQuery()
        End Using
    End Sub

    Private Sub _RemoveSchool(itemId As Integer)
        Using connection As New SqlConnection(Logic.Database.ConnectionString)
            connection.Open()
            Dim cmd As New SqlCommand(
                "DELETE FROM web_DriverApplicationSchools WHERE id=@itemId",
                connection)
            cmd.Parameters.AddWithValue("itemId", itemId)
            cmd.ExecuteNonQuery()
        End Using
    End Sub

#End Region

End Class