# mypy: ignore-errors
import os

from ndspy.rom import NintendoDSRom

from skytemple_files.common.util import get_ppmdu_config_for_rom
from skytemple_files.container.dungeon_bin.handler import DungeonBinHandler
from skytemple_files.container.dungeon_bin.sub.sir0_dpla import DbinSir0DplaHandler
from skytemple_files.graphics.dpla.handler import DplaHandler

base_dir = os.path.join(os.path.dirname(__file__), '..', '..', '..', '..', '..')

rom = NintendoDSRom.fromFile(os.path.join(base_dir, 'skyworkcopy_us.nds'))

dungeon_bin_bin = rom.getFileByName('DUNGEON/dungeon.bin')
static_data = get_ppmdu_config_for_rom(rom)
dungeon_bin = DungeonBinHandler.deserialize(dungeon_bin_bin, static_data)

for i, m in enumerate(dungeon_bin):
    if dungeon_bin.get_filename(i).endswith('.dpla'):
        before = dungeon_bin.get_files_bytes()[i]
        after = DbinSir0DplaHandler.serialize(m)
        print(i)
        with open('/tmp/before.bin', 'wb') as f:
            f.write(before)
        with open('/tmp/after.bin', 'wb') as f:
            f.write(after)
        if i == 81:
            continue  # this one is a bit weird for some reason, but should be ok.
        assert before == after
from skytemple_files.common.tiled_image import TilemapEntry
from skytemple_files.common.types.file_types import FileType
from skytemple_files.common.util import get_ppmdu_config_for_rom, iter_bytes, \
    read_u16, write_u16
from skytemple_files.container.dungeon_bin.handler import DungeonBinHandler

output_dir = os.path.join(os.path.dirname(__file__), 'dbg_output')
base_dir = os.path.join(os.path.dirname(__file__), '..', '..', '..', '..', '..')
os.makedirs(os.path.join(output_dir, 'raw'), exist_ok=True)

rom = NintendoDSRom.fromFile(os.path.join(base_dir, 'skyworkcopy_us.nds'))

dungeon_bin_bin = rom.getFileByName('DUNGEON/dungeon.bin')
static_data = get_ppmdu_config_for_rom(rom)
dungeon_bin = DungeonBinHandler.deserialize(dungeon_bin_bin, static_data)

# CHECK 1: We can serialize bin packs correctly
dungeon_bin_bin_after = DungeonBinHandler.serialize(dungeon_bin)
assert dungeon_bin_bin == dungeon_bin_bin_after


# -- CORUPTION TASKS
def corrupt171():
    """Corrupt 171: Dungeon tiles Beach cave 1? -- No actually not.
    Seems to be some kind of map assembling information."""
    img171 = dungeon_bin[171].decompress()
    # Make the first entry tile 2
    img171 = b'\x02' * len(img171)
    dungeon_bin[171] = FileType.COMMON_AT.compress(img171)