Imports System.IO
Imports VERAG_PROG_ALLGEMEIN

Public Class frmVorauskasse_CBAM
    Public GesamtBetrag As Double = 0
    Public Aufschlag As Double = 0

    Public autocalc = False


    Private Sub frmVorauskasse_ZollBerechnen_Load(sender As Object, e As EventArgs) Handles Me.Shown
        With MyDatagridview1
            .Columns(0).DefaultCellStyle.Format = ""
            .Columns(1).DefaultCellStyle.Format = "N2"
            .Columns(4).DefaultCellStyle.Format = "N2"
        End With
        txtCalc_Defaut_CertPrice._value = 95
        MyDatagridview1.Columns("clmnCountry").ReadOnly = False
        If autocalc Then
            Button7.PerformClick()
        End If
    End Sub

    Private Sub Button7_Click(sender As Object, e As EventArgs) Handles Button7.Click
        'If e.ColumnIndex = 2 Then Exit Sub
        GesamtBetrag = 0
        For Each r As DataGridViewRow In MyDatagridview1.Rows
            If Not r.IsNewRow Then
                Dim cost As Double = 0
                Dim emission As Double = 0
                Dim benchmark As Double = 0
                cATEZ_Greenpulse_CBAM_CostCalculation.calcCBAM_ByCertificatePrice(r.Cells("clmnTarif").Value, r.Cells("clmnWeight").Value, r.Cells("clmnCountry").Value, txtCalc_Defaut_CertPrice._value, r.Cells("clmnYear").Value, cost, emission, benchmark)

                If cost > 0 Then
                    r.Cells("clmnKosten").Value = CDbl(cost.ToString("N2"))
                    r.Cells("cmlnEmission").Value = emission
                    r.Cells("clmnBenchmark").Value = benchmark
                    GesamtBetrag += cost
                End If

            End If
        Next
        Label1.Text = GesamtBetrag.ToString("C2")
        Aufschlag = (GesamtBetrag * CDbl(MyTextBox1._value))
        If IsNumeric(MyTextBox1._value) Then Label2.Text = (GesamtBetrag * CDbl(MyTextBox1._value)).ToString("C2")
    End Sub

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim dt As New DataTable()
        With dt.Columns
            .Add("Tariff", GetType(String))
            .Add("Weight", GetType(Decimal))
            .Add("Country", GetType(String))
            .Add("Year", GetType(Integer))
            .Add("Costs", GetType(Decimal))
            .Add("Emission", GetType(Decimal))
        End With

        For Each r As DataGridViewRow In MyDatagridview1.Rows
            If r.IsNewRow Then Continue For

            dt.Rows.Add(
                r.Cells("clmnTarif").Value,
                If(r.Cells("clmnWeight").Value, 0D),
                r.Cells("clmnCountry").Value,
                If(r.Cells("clmnYear").Value, Nothing),
                If(r.Cells("clmnKosten").Value, Nothing),
                If(r.Cells("cmlnEmission").Value, Nothing)
        )
        Next
        cProgramFunctions.genExcelFromDT_NEW(dt, {"E:E"},, "CBAM Kosten",,,,,,, True)
    End Sub

    Public Function getValues() As DataTable
        Dim dt As New DataTable()

        ' Spalten anlegen
        For Each col As DataGridViewColumn In MyDatagridview1.Columns
            dt.Columns.Add(col.Name, GetType(String)) ' oder passenden Typ setzen
        Next

        ' Zeilen kopieren
        For Each row As DataGridViewRow In MyDatagridview1.Rows
            If Not row.IsNewRow Then
                Dim dr As DataRow = dt.NewRow()

                For Each col As DataGridViewColumn In MyDatagridview1.Columns
                    dr(col.Name) = If(row.Cells(col.Name).Value, DBNull.Value)
                Next

                dt.Rows.Add(dr)
            End If
        Next
        dt.TableName = "cbamdata"
        Return dt
    End Function

    Public Function getValues_DATA() As String
        Try
            Dim sw As New StringWriter()
            Dim dt = getValues()
            dt.WriteXml(sw, XmlWriteMode.WriteSchema)
            Return sw.ToString()
        Catch ex As Exception
            MsgBox("Fehler beim Exportieren der Daten: " & ex.Message & ex.StackTrace, MsgBoxStyle.Critical)
        End Try
        Return ""
    End Function

    Public Sub setValues_DATA(data As String)
        Try
            If data Is Nothing Then Exit Sub
            If data = "" Then Exit Sub

            Dim dt As New DataTable()
            Dim sr As New StringReader(data)
            dt.ReadXml(sr)
            setValues(dt)
        Catch ex As Exception
            MsgBox("Fehler beim Laden der Daten: " & ex.Message, MsgBoxStyle.Critical)
        End Try
    End Sub

    Public Shared Function DATA_to_String(data As String) As String
       Return  DataTableToString_First4Cols(DATA_to_dt(data))
    End Function
    Public Shared Function DATA_to_dt(data As String) As DataTable
        Try
            If data Is Nothing Then Return Nothing
            If data = "" Then Return Nothing

            Dim dt As New DataTable()
            Dim sr As New StringReader(data)
            dt.ReadXml(sr)
            Return dt
        Catch ex As Exception
            MsgBox("Fehler beim Laden der Daten: " & ex.Message, MsgBoxStyle.Critical)
        End Try
        Return Nothing
    End Function

    Public Shared Function DataTableToString_First4Cols(dt As DataTable) As String

        If dt Is Nothing OrElse dt.Columns.Count = 0 Then
            Return String.Empty
        End If

        Dim sb As New System.Text.StringBuilder()

        ' Anzahl der zu verwendenden Spalten (max 5)
        Dim colCount As Integer = Math.Min(5, dt.Columns.Count)

        ' ---- Überschrift ----
        For i As Integer = 0 To colCount - 1
            sb.Append(dt.Columns(i).ColumnName.Replace("clmn", ""))

            If i < colCount - 1 Then
                sb.Append(" | ")
            End If
        Next

        sb.AppendLine()
        sb.AppendLine(New String("-"c, 50))

        ' ---- Zeilen ----
        For Each dr As DataRow In dt.Rows

            For i As Integer = 0 To colCount - 1

                Dim value As Object = dr(i)

                If value Is DBNull.Value OrElse value Is Nothing Then
                    sb.Append("")
                Else
                    sb.Append(value.ToString())
                End If

                If i < colCount - 1 Then
                    sb.Append(" | ")
                End If

            Next

            sb.AppendLine()
        Next

        Return sb.ToString()

    End Function

    Public Sub setValues(dt As DataTable)
        Try
            ' WICHTIG: Auto-Generierung verhindern
            MyDatagridview1.AutoGenerateColumns = False

            ' Falls vorher gebunden war: Binding lösen, damit nichts auto-generiert
            If MyDatagridview1.DataSource IsNot Nothing Then
                MyDatagridview1.DataSource = Nothing
            End If

            ' Nur Zeilen löschen – Spalten bleiben
            MyDatagridview1.Rows.Clear()

            If dt Is Nothing OrElse dt.Rows.Count = 0 Then Return

            MyDatagridview1.SuspendLayout()

            For Each dr As DataRow In dt.Rows
                Dim rowIndex = MyDatagridview1.Rows.Add()

                For Each col As DataGridViewColumn In MyDatagridview1.Columns
                    ' getValues() nutzt col.Name -> daher hier auch col.Name
                    If dt.Columns.Contains(col.Name) Then
                        Dim v As Object = dr(col.Name)
                        MyDatagridview1.Rows(rowIndex).Cells(col.Index).Value =
                        If(v Is DBNull.Value, Nothing, v)
                    End If
                Next
            Next

        Catch ex As Exception
            MsgBox("Fehler beim Laden der Daten: " & ex.Message, MsgBoxStyle.Critical)
        Finally
            MyDatagridview1.ResumeLayout()
        End Try
    End Sub
End Class