Imports System.Windows.Forms.VisualStyles.VisualStyleElement.TextBox

Public Class CityEditor

    Public files1 As List(Of fileInfo)
    Public files2 As List(Of fileInfo)
    Public CurFile As rleFile
    Public CurFileUnrle As Byte()
    Public EngFile As rleFile
    Public EngFileUnrle As Byte()


    Private Sub DungeonEditor_Load(sender As Object, e As EventArgs) Handles MyBase.Load

        Dim cd = New ISOTools

        'Reading filetable and make array
        files1 = cd.makeFileList(Form1.UserPath.Text)
        files2 = cd.makeFileList(Form1.EngISOPath.Text)


        LoadDistrict()
    End Sub

    Private Sub SecondVariant_CheckedChanged(sender As Object, e As EventArgs) Handles SecondVariant.CheckedChanged
        LoadDistrict()
    End Sub

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        If ID.Text = 713 Then
            ID.Text = 719
        Else
            ID.Text -= 1
        End If

        LoadDistrict()
    End Sub

    Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
        If ID.Text = 719 Then
            ID.Text = 713
        Else
            ID.Text += 1
        End If

        LoadDistrict()
    End Sub


    Public Sub LoadDistrict()

        Dim cd = New ISOTools
        Dim rle = New rleTools

        Form1.DeconstructFile(cd.getCDfile(Form1.UserPath.Text, files1(ID.Text).Sector, files1(ID.Text).Sizw).ToArray)    'here is separated binfile
        CurFile = Form1.binFile(Form1.binFile.Count - 3 + Convert.ToInt32(SecondVariant.Checked)) 'Get Before Last File
        CurFileUnrle = rle.UnrleNocompr(CurFile.Bytes).ToArray
        Form1.DeconstructFile(cd.getCDfile(Form1.EngISOPath.Text, files2(ID.Text).Sector, files2(ID.Text).Sizw).ToArray)    'here is separated binfile
        EngFile = Form1.binFile(Form1.binFile.Count - 3 + Convert.ToInt32(SecondVariant.Checked)) 'Get Before Last File
        EngFileUnrle = rle.UnrleNocompr(EngFile.Bytes).ToArray
        'Dim curfile As rleFile = binFile(8)

        Dim JapBlock1Len = CurFileUnrle(0)
        Dim JapBlock2Len = CurFileUnrle(1)
        Dim JapBlockLines = CurFileUnrle(2)
        Dim EnBlock1Len = EngFileUnrle(0)
        Dim EnBlock2Len = EngFileUnrle(1)
        Dim EnBlockLines = EngFileUnrle(2)

        Dim JapTextStart = JapBlock1Len * 16 + JapBlock2Len * 8 + 4     'header 8 + head 4 block
        Dim EngTextStart = EnBlock1Len * 16 + EnBlock2Len * 8 + 4

        Try
            EngTitle.Text = readEngText(EngTextStart + 4) 'after coords...
            UserTitle.Text = readRusText(JapTextStart + 4) 'after coords...
            DataGridView1.Rows.Clear()

            For a = 1 To JapBlockLines - 1
                JapTextStart += 40
                EngTextStart += 40          'Move to Next Block...
                Dim jap_X As String = BitConverter.ToInt16(CurFileUnrle, JapTextStart)
                Dim jap_Y As Integer = BitConverter.ToInt16(CurFileUnrle, JapTextStart + 2)
                Dim japLoc = readRusText(JapTextStart + 4 + 14) ' aftercoords

                Dim en_coords As String = BitConverter.ToInt16(CurFileUnrle, EngTextStart) & " x " & BitConverter.ToInt16(CurFileUnrle, EngTextStart + 2)
                Dim enLoc = readEngText(JapTextStart + 4 + 14) ' aftercoords
                DataGridView1.Rows.Add(jap_X, jap_Y, japLoc, enLoc, en_coords)
            Next

        Catch ex As Exception
            MsgBox("Error reading this district. Try another variant.")
        End Try

    End Sub

    Public Function readEngText(ByVal Curbt As Integer)
        Dim a = ""
        Do
            If EngFileUnrle(Curbt) = 3 Or EngFileUnrle(Curbt) = 0 Then Exit Do
            If EngFileUnrle(Curbt) > 128 Then EngFileUnrle(Curbt) = Asc("-")
            a &= Chr(EngFileUnrle(Curbt))
            Curbt += 1
        Loop
        Return a
    End Function


    Public Function readRusText(ByVal Curbt As Integer)
        Dim a = ""
        If BitConverter.ToInt16(CurFileUnrle, Curbt) And &H2000 Then
            Dim len = BitConverter.ToInt16(CurFileUnrle, Curbt) And &HFF
            Curbt += 2
            For b = 0 To len - 1
                a &= Chr(CurFileUnrle(Curbt))
                Curbt += 1
            Next
        Else
            Dim b = BitConverter.ToInt16(CurFileUnrle, Curbt)

            Do
                Dim curChar = BitConverter.ToInt16(CurFileUnrle, Curbt)
                If (curChar < &H1000) Then a &= Form1.chars(curChar)
                'a &= CurFileUnrle(Curbt).ToString("X2") & CurFileUnrle(Curbt + 1).ToString("X2")
                Curbt += 2
                If Curbt >= CurFileUnrle.Count Then Exit Do
                b = BitConverter.ToInt16(CurFileUnrle, Curbt)
            Loop Until (b And &H1000)
        End If
        Return a
    End Function

    Private Sub UserTitle_TextChanged(sender As Object, e As EventArgs) Handles UserTitle.TextChanged
        ChrCount.Text = UserTitle.Text.Length
        If UserTitle.Text.Length > 14 Then
            ChrCount.ForeColor = Color.Red
        Else
            ChrCount.ForeColor = Color.DarkGreen
        End If
    End Sub
    Private Sub DataGridView1_CurrentCellChanged(sender As Object, e As EventArgs) Handles DataGridView1.CurrentCellChanged
        If IsNothing(DataGridView1.CurrentCell) Then Exit Sub
        Dim a = DataGridView1.CurrentCell.Value.ToString.Length
        AreaCount.Text = a
        If a > 20 Then
            AreaCount.ForeColor = Color.Red
        Else
            AreaCount.ForeColor = Color.DarkGreen
        End If
    End Sub

    Private Sub Button3_Click(sender As Object, e As EventArgs) Handles SaveToISO.Click
        'CHANGING FILE!

        Dim cd = New ISOTools
        Dim rle = New rleTools

        'Dim curfile As rleFile = binFile(8)

        Dim JapBlock1Len = CurFileUnrle(0)
        Dim JapBlock2Len = CurFileUnrle(1)
        Dim JapBlockLines = CurFileUnrle(2)

        Dim JapTextStart = JapBlock1Len * 16 + JapBlock2Len * 8 + 4     'header 8 + head 4 block

        MakeSaveRussianString(UserTitle.Text, 14, JapTextStart + 4)
        CurFileUnrle(18) = 0
        CurFileUnrle(19) = 10


        For Each row In DataGridView1.Rows

            JapTextStart += 40
            Dim xxx = Convert.ToInt16(row.Cells(0).Value)
            Dim yyy = Convert.ToInt16(row.Cells(1).Value)
            CurFileUnrle(JapTextStart) = BitConverter.GetBytes(xxx)(0)
            CurFileUnrle(JapTextStart + 1) = BitConverter.GetBytes(xxx)(1)
            CurFileUnrle(JapTextStart + 2) = BitConverter.GetBytes(yyy)(0)
            CurFileUnrle(JapTextStart + 3) = BitConverter.GetBytes(yyy)(1)
            Dim japLoc = readRusText(JapTextStart + 4 + 14)
            MakeSaveRussianString(Trim(row.Cells(2).Value), 22, JapTextStart + 4 + 14)
        Next

        Form1.DeconstructFile(cd.getCDfile(Form1.UserPath.Text, files1(ID.Text).Sector, files1(ID.Text).Sizw).ToArray)  'Deconstruct again!
        Form1.binFile(Form1.binFile.Count - 3 + Convert.ToInt32(SecondVariant.Checked)).Bytes = rle.attachNoCompressionHeader(CurFile, CurFileUnrle).ToArray

        'Packing
        Dim finalPack = New List(Of Byte)
        For Each bin In Form1.binFile
            finalPack.AddRange(bin.Bytes)

            'Adding SectorGaps (ONLY FOR CITY DISTRICTS!!!!!!!)
            Dim gap = 2048 - (finalPack.Count Mod 2048)
            For g = 0 To gap - 1
                finalPack.Add(0)
            Next

        Next


        Dim beforePackSize As Integer = cd.getCDfile(Form1.UserPath.Text, files1(ID.Text).Sector, files1(ID.Text).Sizw).Count

        If finalPack.Count = beforePackSize Then
            'If sizw matched

            cd.saveCDfile(Form1.UserPath.Text, files1(ID.Text).Sector, finalPack.Count, finalPack.ToArray)

        ElseIf MsgBox($"finalPack is not match source :( {vbCrLf} Source size {beforePackSize}{vbCrLf} Final Pack Size {finalPack.Count} {vbCrLf} Wanna save it to a file for inspect?", MsgBoxStyle.YesNo) = MsgBoxResult.Yes Then
            My.Computer.FileSystem.WriteAllBytes(Form1.SaveFileDialog1.FileName, finalPack.ToArray, False)
        End If

    End Sub

    Public Sub MakeSaveRussianString(ByVal str As String, ByVal maxBytes As Integer, ByVal offs As String)
        Dim a = New List(Of Byte)
        If str = "0010" Then
            For zzz = 0 To maxBytes - 1 Step 2
                CurFileUnrle(offs + zzz) = 0
                CurFileUnrle(offs + zzz + 1) = &H10
            Next
            Exit Sub

        End If


        a.Add(str.Length)
        a.Add(&H20)
        For zzz = 0 To str.Length - 1
            a.Add(Asc(str(zzz)))
        Next
        '        a.Add(0)
        '       a.Add(&H10)

        For zzz = 0 To maxBytes - str.Length - 3
            a.Add(0)
        Next
        For zzz = 0 To maxBytes - 1
            CurFileUnrle(zzz + offs) = a(zzz)
        Next
    End Sub


End Class