Imports System.Data.SqlClient
Imports System.Threading
Imports Logic.DateExtensions
Imports Logic.NullableDateExtensions

Public Class EditServiceItem
    Inherits System.Web.UI.Page
    
    Property contractId As Integer
    Property vehicleId As Integer
    Property itemId As Integer
    
    Protected Sub Page_Load() Handles Me.Load
        Try

            itemId = Logic.Conversion.ToInteger(Request.Params("id"))
            vehicleId = Logic.Conversion.ToInteger(Request.Params("vid"))
            contractId = Logic.Conversion.ToInteger(Request.Params("cid"))

            ' Load vehicle and contract ids
            Using connection As New SqlConnection(Logic.Database.connectionString)
                connection.Open()
                Dim cmd As New SqlCommand("", connection)
                If itemId > 0 Then
                    cmd.CommandText = "SELECT vehicleId FROM VehicleServiceItems WHERE id=@itemId"
                    cmd.Parameters.AddWithValue("itemId", itemId)
                    vehicleId = Logic.Conversion.ToInteger(cmd.ExecuteScalar())
                End If
                If vehicleId > 0 Then
                    cmd.CommandText = "SELECT contractId FROM Vehicle WHERE ID=@vehicleId"
                    cmd.Parameters.AddWithValue("vehicleId", vehicleId)
                    contractId = Logic.Conversion.ToInteger(cmd.ExecuteScalar())
                End If
            End Using

            ' Validate params
            If contractId = 0 Then
                Throw New Exception(String.Format("Invalid item id ({0}), vehicle id ({1}), or contract id ({2}).", itemId, vehicleId, contractId))
            End If

            ' Ensure we have permission
            Master.CurrentClient.VerifyContractAccess(contractId)
            Dim perms = Master.CurrentClient.Permissions
            If Not perms.Contains("Edit Vehicle Service Items") Then Throw New HttpException(403, "Forbidden")

            ' Fill in data
            _FillUI()
            If Not Page.IsPostBack Then
                Master.SetParentPage("Vehicles.aspx?cid=" & contractId)
                _UpdatePermissions()
                _FillData(itemId)
            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
        If vehicleId > 0 Then
            Response.Redirect("EditVehicle.aspx?id=" & vehicleId & "&cid=" & contractId)
        Else
            Response.Redirect("Vehicles.aspx?cid=" & contractId)
        End If
    End Sub

    Private Sub btnSave_Click() Handles btnSave.Click
        If Not Page.IsValid Then
            Exit Sub
        End If
        Try

            Dim username = "[Web: " & Master.CurrentClient.username & "]"

            Dim serviceItem = If(itemId, New Logic.VehicleServiceItem(itemId), New Logic.VehicleServiceItem)
            _GetData(serviceItem)
            serviceItem.Save(username)

            If vehicleId > 0 Then
                Response.Redirect("EditVehicle.aspx?id=" & vehicleId & "&cid=" & contractId)
            Else
                Response.Redirect("Vehicles.aspx?cid=" & contractId)
            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 valServiceType_ServerValidate(sender As Object, e As ServerValidateEventArgs) Handles valServiceType.ServerValidate
        e.IsValid = (ddlServiceType.SelectedValue <> 0)
    End Sub


    Private Sub _FillData(itemId As Integer)
        Dim serviceItem = If(itemId, New Logic.VehicleServiceItem(itemId), New Logic.VehicleServiceItem)
        With serviceItem
            If .id = 0 Then .vehicleId = vehicleId
            If .scheduleId.HasValue Then
                ddlServiceType.SelectedValue = CInt(.scheduleId)
            Else
                ddlServiceType.SelectedValue = 0
            End If
            txtMechanic.Text = .mechanic
            ddlVehicle.SelectedValue = .vehicleId
            dtService.Text = .serviceDate.FormatForHtml5()
            dtNextService.Text = .nextServiceDate.FormatForHtml()
            txtDescription.Text = .description
            txtOdometer.Text = If(.miles, "")
            txtCost.Text = If(.cost, "")
        End With
    End Sub

    Private Sub _FillUI()
        Using connection As New SqlConnection(Logic.Database.connectionString)
            connection.Open()

            Dim cmd As New SqlCommand("", connection)
            cmd.Parameters.AddWithValue("contractId", contractId)
            cmd.Parameters.AddWithValue("vehicleId", vehicleId)

            ' Load vehicles
            Dim selectedVehicle = ddlVehicle.SelectedValue
            ddlVehicle.Items.Clear()
            ddlVehicle.Items.Add(New ListItem("(all)", 0))
            cmd.CommandText = 
                "SELECT id, unit, vin FROM Vehicle
                WHERE (contractId=@contractId AND @contractId<>0) OR id=@vehicleId
                ORDER BY unit, vin, id"
            Using dReader = cmd.ExecuteReader()
                While dReader.Read()
                    Dim name = "unit:" & dReader(1) & " - vin:" & dReader(2) & " - id:" & dReader(0)
                    ddlVehicle.Items.Add(New ListItem(name, dReader(0)))
                End While
            End Using
            ddlVehicle.SelectedValue = selectedVehicle

            ' Load service types and their schedules
            Dim selectedType = ddlServiceType.SelectedValue
            Dim daySchedules As New List(Of Integer)
            ddlServiceType.Items.Clear()
            ddlServiceType.Items.Add(New ListItem("", 0))
            cmd.CommandText = 
                "SELECT cSchedules.id, label, daySchedule, mileageSchedule
                FROM VehicleMaintenanceSchedules vSchedules
                LEFT JOIN MaintenanceSchedules cSchedules ON vSchedules.scheduleId=cSchedules.id
                WHERE isActive=1 AND (
                    (vSchedules.vehicleId=@vehicleId AND @vehicleId>0) OR
                    (@vehicleId=0 AND contractId=@contractId))
                GROUP BY cSchedules.id, label, daySchedule, mileageSchedule -- contract returns multiple
                ORDER BY label"
            Using dReader = cmd.ExecuteReader()
                While dReader.Read()
                    ddlServiceType.Items.Add(New ListItem(dReader(1), dReader(0)))
                    daySchedules.Add(Logic.Conversion.ToInteger(dReader(2)))
                End While
            End Using
            litDaySchedules.Text = String.Join(",", daySchedules)
            ddlServiceType.SelectedValue = selectedType

        End Using
    End Sub

    Private Sub _GetData(serviceItem As Logic.VehicleServiceItem)
        With serviceItem
            .vehicleId = ddlVehicle.SelectedValue
            .scheduleId = ddlServiceType.SelectedValue
            .mechanic = txtMechanic.Text
            .label = ddlServiceType.SelectedItem.Text
            .serviceDate = Logic.Conversion.ToDate(dtService.Text)
            .nextServiceDate = Logic.Conversion.ToNullableDate(dtNextService.Text)
            .description = txtDescription.Text
            .miles = Logic.Conversion.ToNullableInteger(txtOdometer.Text)
            .cost = Logic.Conversion.ToNullableDouble(txtCost.Text)
            .contractId = contractId
        End With
    End Sub

    Private Sub _UpdatePermissions()
        Dim perms = Master.CurrentClient.Permissions
        If Not perms.contains("Edit Vehicle Service Items") Then
            Throw New Exception("Permission has not been granted for this action.")
        End If
    End Sub

End Class