Imports System.Data.SqlClient
Imports System.IO

Public Class Drivers
    Inherits System.Web.UI.Page

    Property contractId As Integer

    Public Overrides Sub VerifyRenderingInServerForm(ByVal control As System.Web.UI.Control)
        ' Do NOT call MyBase.VerifyRenderingInServerForm
    End Sub

    Private Sub btnExport_Click(sender As Object, e As EventArgs) Handles btnExport.Click
        Response.Clear()
        Response.Buffer = True
        Response.ClearContent()
        Response.ClearHeaders()
        Response.Charset = ""
        Dim FileName As String = "DriverList_" & contractId & ".xls"
        Dim strwritter As New StringWriter
        Dim HTMLTextWrtter As New HtmlTextWriter(strwritter)
        Response.Cache.SetCacheability(HttpCacheability.NoCache)
        Response.ContentType = "application/vnd.ms-excel"
        Response.AddHeader("Content-Disposition", "attachment;filename=" + FileName)
        gvDrivers.GridLines = GridLines.Both
        gvDrivers.HeaderStyle.Font.Bold = True
        gvDrivers.RenderControl(HTMLTextWrtter)
        Response.Write(strwritter.ToString())
        Response.End()

    End Sub


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

            contractId = Logic.Conversion.ToInteger(Request.Params("cid"))
            Master.CurrentClient.VerifyContractAccess(contractId)

            Dim perms = Master.CurrentClient.Permissions
            If Not perms.Contains("View Drivers Page") Then Throw New HttpException(403, "Forbidden")
            'If Not perms.Contains("Move Driver") OrElse Not _IsAgencyOrSubcontract() Then
            '    Dim colCount = gvDrivers.Columns.Count
            '    gvDrivers.Columns(colCount - 2).Visible = False
            '    gvDrivers.Attributes.Add("data-fixed-right-number", "1")
            'Else
            '    gvDrivers.Attributes.Add("data-fixed-right-number", "2")
            'End If
            If perms.Contains("Move Driver") Then
                gvDrivers.Attributes.Add("data-fixed-right-number", "3")
            Else
                Dim colCount = gvDrivers.Columns.Count
                gvDrivers.Columns(colCount - 3).Visible = False
                gvDrivers.Attributes.Add("data-fixed-right-number", "2")
            End If

            dsDrivers.ConnectionString = Logic.Database.ConnectionString
            dsDrivers.SelectParameters("contractId").DefaultValue = contractId

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

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


    Private Sub btnAdd_Click(sender As Object, e As EventArgs) Handles btnAdd.Click
        Response.Redirect("EditDriver.aspx?cid=" & contractId)
    End Sub

    Private Sub gvDrivers_RowDataBound(sender As Object, e As GridViewRowEventArgs) Handles gvDrivers.RowDataBound
        If e.Row.RowType = DataControlRowType.DataRow Then
            Dim data As DataRowView = e.Row.DataItem
            Dim url = String.Format("EditDriver.aspx?id={0}&cid={1}", data("id"), data("ContractID"))
            e.Row.Attributes.Add("data-href", url)
        End If
    End Sub

    Private Function _IsAgencyOrSubcontract() As Boolean
        Using connection As New SqlConnection(Logic.Database.connectionString)
            connection.Open()
            Dim cmd As New SqlCommand(
                "SELECT
                    ISNULL(sc.IsEmploymentAgency,0) isEmploymentAgency,
                    ISNULL(c.OwnerContractId,0) isSubcontract
                FROM ServiceContract sc LEFT JOIN Customer c ON c.ID=sc.CustomerID
                WHERE sc.ID=@contractId", connection)
            cmd.Parameters.AddWithValue("contractId", contractId)
            Dim dReader = cmd.ExecuteReader()
            If Not dReader.Read() Then Return False
            Return CBool(dReader(0)) Or CBool(dReader(1))
        End Using
    End Function

End Class