Public Class DungeonEditor

    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)


        LoadDungeon()
    End Sub

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


        LoadDungeon()
    End Sub

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


        LoadDungeon()
    End Sub


    Public Sub LoadDungeon()

        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(0)
        CurFileUnrle = rle.Unrle(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(0)
        EngFileUnrle = rle.Unrle(EngFile.Bytes).ToArray
        'Dim curfile As rleFile = binFile(8)

        EngTitle.Text = readEngText(0)
        UserTitle.Text = readRusText(0)


        Dim pointer As Int32 = BitConverter.ToInt32(CurFileUnrle, 104)
        Dim endByte As Int32 = BitConverter.ToInt32(CurFileUnrle, 60)
        DataGridView1.Rows.Clear()

        Do

            If pointer >= endByte Then Exit Do

            Dim status = BitConverter.ToInt16(CurFileUnrle, pointer)
            Dim statusE = EngFileUnrle(pointer)

            pointer += 2
            Dim engString = readEngText(pointer - 1)
            Dim rustext = readRusText(pointer)

            DataGridView1.Rows.Add(status, rustext, engString, statusE)
            pointer += 30
        Loop

        '32 - floors count
        '36-52 - floors ids (by 1 byte)

        'FLOOR STRUCTURE FROM 52 (40 bytes chunks)
        '{
        'int16 + int16 - Map width and (Heigth / 2) in words, or normal minimap by 1 byte
        'int32 - FFFF0000
        'int32 - Flood id
        'int32 - Objects geometry offset
        'int32 - Collisions & scripts attach map
        'int32 - Map & labels offset
        'int32 - Some vars offset 1
        'int32 - Some vars offset 2 (coords??)
        'int32 - Some vars offset 3
        'int32 - Floor places strings offset (int16 - status, char[30] - text)
        '}
        '80 - Minimap offset
        '84 - DUNGEON MAIN MAP offset
        '88 - Dungeon normal usermap offset


        'script attach table
        ' - script parameter int8 - ID, int 4 - type/collision, int4 - anim type
        ' - idC8/idCC - block and run object script
        ' - xx28/xx28 - execute on step trigger
        ' - id2C - show and run character script
        ' - 00A0 - show text window
        ' - idB0 - take item (item table = 800c692c)

    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
        If IsNothing(DataGridView1.CurrentCell.Value) 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

        'Making title bytes
        MakeSaveRussianString(UserTitle.Text, 24, 0)

        Dim off As Int32 = BitConverter.ToInt32(CurFileUnrle, 104)
        'Dim pointer As Int32 = BitConverter.ToInt32(CurFileUnrle, 104)
        Dim endByte As Int32 = BitConverter.ToInt32(CurFileUnrle, 60)


        For Each row In DataGridView1.Rows

            CurFileUnrle(off) = row.Cells(0).Value
            CurFileUnrle(off + 1) = 0

            MakeSaveRussianString(Trim(row.Cells(1).Value), 30, off + 2)

            off += 32
        Next


        Form1.DeconstructFile(cd.getCDfile(Form1.UserPath.Text, files1(ID.Text).Sector, files1(ID.Text).Sizw).ToArray)    'here is separated binfile
        Dim curfile = Form1.binFile(0)

        Dim before = curfile.Bytes.Count
        Form1.binFile(0).Bytes = rle.decodeRLEnew(CurFileUnrle, curfile).ToArray
        Form1.binFile(0).BytesAfter = 0
        Dim after = Form1.binFile(0).Bytes.Count

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

            'AddingBytesAfter
            For g = 0 To bin.BytesAfter - 1
                finalPack.Add(0)
            Next

        Next


        If finalPack.Count Mod 2048 > 0 Then
            For g = 1 To (2048 - (finalPack.Count Mod 2048))
                finalPack.Add(0)
            Next g
        End If

        Dim beforeSize As Integer = files1(ID.Text).Sizw

        If finalPack.Count <= files1(ID.Text).Sizw Then
            'If sizw matched

            cd.saveCDfile(Form1.UserPath.Text, files1(ID.Text).Sector, finalPack.Count, finalPack.ToArray)
            MsgBox("Succesfully Saved!" & vbCrLf & "Bofore: " & before & vbCrLf & "Afta: " & after & vbCrLf & after - before & "b.")

            Exit Sub
        End If


        If MsgBox("finalPack is Bigger than source :(" &
                vbCrLf & "Bofore: " & before & vbCrLf & "Afta: " & after & vbCrLf & after - before & "b." &
                vbCrLf & "Do you wanna save it to file?", MsgBoxStyle.YesNo) = MsgBoxResult.Yes Then

            If Form1.SaveFileDialog1.ShowDialog <> DialogResult.OK Then Exit Sub

            My.Computer.FileSystem.WriteAllBytes(Form1.SaveFileDialog1.FileName, finalPack.ToArray, False)
        End If



        'My.Computer.FileSystem.WriteAllBytes("D:\Games\PSX\Persona.2.Innocent.Sin\Export\UnRLE\0097\EDITOR_TEST", CurFileUnrle, False)


    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 x = 0 To maxBytes - 1 Step 2
                CurFileUnrle(offs + x) = 0
                CurFileUnrle(offs + x + 1) = &H10
            Next
            Exit Sub

        End If


        a.Add(str.Length)
        a.Add(&H20)
        For x = 0 To str.Length - 1
            a.Add(Asc(str(x)))
        Next
        For x = 0 To maxBytes - str.Length - 3
            a.Add(0)
        Next
        For x = 0 To maxBytes - 1
            CurFileUnrle(x + offs) = a(x)
        Next
    End Sub
End Class