Imports System.Data.SqlClient
Imports System.Threading

Public Class RemoveSchedule
    Inherits System.Web.UI.Page

    Property contractId As Integer
    Property scheduleId As Integer

    Private Sub Page_Load() Handles Me.Load
        Try

            scheduleId = Logic.Conversion.ToInteger(Request.Params("id"))

            Using connection As New SqlConnection(Logic.Database.connectionString)
                connection.Open()
                Dim cmd As New SqlCommand("SELECT contractId FROM MaintenanceSchedules WHERE id=@scheduleId", connection)
                cmd.Parameters.AddWithValue("scheduleId", scheduleId)
                contractId = cmd.ExecuteScalar()
            End Using

            Master.CurrentClient.VerifyContractAccess(contractId)

            Dim perms = Master.CurrentClient.Permissions
            If Not perms.Contains("Edit Maintenance Schedules") Then Throw New HttpException(403, "Forbidden")

            If Not Page.IsPostBack Then
                Master.SetParentPage("Vehicles.aspx?cid=" & contractId)
                _FillData(scheduleId)
            End If

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

    Private Sub btnCancel_Click() Handles btnCancel.Click
        Response.Redirect("Vehicles.aspx?cid=" & contractId)
    End Sub

    Private Sub btnDelete_Click() Handles btnDelete.Click
        If Not Page.IsValid Then
            Exit Sub
        End If

        Try
            Using connection As New SqlConnection(Logic.Database.connectionString)
                connection.Open()

                Dim cmd As New SqlCommand("UPDATE MaintenanceSchedules SET isActive=0 WHERE id=@scheduleId", connection)
                cmd.Parameters.AddWithValue("scheduleId", scheduleId)
                cmd.ExecuteScalar()
            End Using
        Catch ex As Exception
            Dim errorId = Logic.Error.Log(ex)
            Response.Redirect("/Error.aspx?id=" & errorId)
        End Try

        Response.Redirect("Vehicles.aspx?cid=" & contractId)

    End Sub

    Private Sub _FillData(scheduleId As Integer)
        Using connection As New SqlConnection(Logic.Database.connectionString)
            connection.Open()

            Dim cmd As New SqlCommand("SELECT * FROM MaintenanceSchedules WHERE id=@scheduleId", connection)
            cmd.Parameters.AddWithValue("scheduleId", scheduleId)

            Dim dReader = cmd.ExecuteReader()
            dReader.Read()

            txtId.Text = dReader("id")
            txtLabel.Text = dReader("label")

        End Using
    End Sub

End Class