"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.OcarinaofTime = void 0;
const EventHandler_1 = require("modloader64_api/EventHandler");
const IModLoaderAPI_1 = require("modloader64_api/IModLoaderAPI");
const PluginLifecycle_1 = require("modloader64_api/PluginLifecycle");
const Z64API = __importStar(require("../API/imports"));
const Z64CORE = __importStar(require("./importsZ64"));
const Z64Lib_1 = require("./Z64Lib");
const ModLoaderAPIInjector_1 = require("modloader64_api/ModLoaderAPIInjector");
const GameAliases_1 = require("./Common/types/GameAliases");
const EventSystem_1 = require("./Common/CommandBuffer/EventSystem");
const OverlayPayload_1 = require("./OverlayPayload");
const MessageContext_1 = __importDefault(require("./OoT/MessageContext"));
const OotAliases_1 = require("./Common/types/OotAliases");
class OcarinaofTime {
    header = [Z64Lib_1.ROM_REGIONS.NTSC_OOT];
    ModLoader;
    link;
    save;
    global;
    helper;
    commandBuffer;
    actorManager;
    msgCtx;
    eventTicks = new Map();
    // Client side variables
    isSaveLoaded = false;
    last_known_scene = -1;
    last_known_room = -1;
    doorcheck = false;
    touching_loading_zone = false;
    frame_count_reset_scene = -1;
    rom_header;
    inventory_cache = Buffer.alloc(0x24, 0xff);
    last_known_age;
    map_select_enabled = false;
    localFlags = Buffer.alloc(0x1c);
    localFlagsTemp = Buffer.alloc(0x1c);
    localFlagsHash = "";
    permFlagsScene = Buffer.alloc(0xb0c);
    permFlagsSceneHash = "";
    heap_start = 0x0;
    heap_size = 0x0;
    isNight = false;
    lastHealth = 0;
    lastTunic = 1 /* Z64API.OoT.Tunic.KOKIRI */;
    preinit() {
        this.ModLoader.config.registerConfigCategory("OcarinaofTime");
        this.ModLoader.config.setData("OcarinaofTime", "skipN64Logo", true);
        this.ModLoader.config.save();
        this.ModLoader.logger.info('OOT VERSION: ' + Z64Lib_1.ROM_VERSIONS[this.rom_header.revision] + '.');
    }
    onReset1(evt) {
        this.isSaveLoaded = false;
    }
    onReset2(evt) {
        this.isSaveLoaded = false;
    }
    init() {
        this.eventTicks.set('waitingForAgeChange', () => {
            if (this.save.age !== this.last_known_age) {
                EventHandler_1.bus.emit(Z64API.Z64.Z64Events.ON_AGE_CHANGE, this.save.age);
                this.last_known_age = this.save.age;
            }
        });
        this.eventTicks.set('waitingForSaveload', () => {
            if (!this.isSaveLoaded && this.helper.isSceneNumberValid()) {
                this.isSaveLoaded = true;
                EventHandler_1.bus.emit(Z64API.Z64.Z64Events.ON_SAVE_LOADED, {});
            }
        });
        this.eventTicks.set('waitingForLoadingZoneTrigger', () => {
            if (this.helper.isLinkEnteringLoadingZone() &&
                !this.touching_loading_zone) {
                EventHandler_1.bus.emit(Z64API.Z64.Z64Events.ON_LOADING_ZONE, {});
                this.touching_loading_zone = true;
            }
        });
        this.eventTicks.set('waitingForFrameCount', () => {
            if (this.global.scene_framecount === 1 &&
                !this.helper.isTitleScreen() &&
                this.helper.isSceneNumberValid()) {
                let cur = this.global.scene;
                this.last_known_scene = cur;
                EventHandler_1.bus.emit(Z64API.Z64.Z64Events.ON_SCENE_CHANGE, this.last_known_scene);
                this.touching_loading_zone = false;
                let inventory = this.ModLoader.emulator.rdramReadBuffer(GameAliases_1.Z64_SAVE + 0x0074, 0x24);
                for (let i = 0; i < inventory.byteLength; i++) {
                    if (inventory[i] === 0x004d) {
                        inventory[i] = this.inventory_cache[i];
                    }
                }
                inventory.copy(this.inventory_cache);
                this.ModLoader.emulator.rdramWriteBuffer(GameAliases_1.Z64_SAVE + 0x0074, inventory);
            }
        });
        this.eventTicks.set('waitingForRoomChange', () => {
            let cur = this.global.room;
            if (this.last_known_room !== cur) {
                this.last_known_room = cur;
                EventHandler_1.bus.emit(Z64API.Z64.Z64Events.ON_ROOM_CHANGE, this.last_known_room);
                this.doorcheck = false;
            }
            let doorState = this.ModLoader.emulator.rdramReadPtr8(GameAliases_1.Z64_GLOBAL_PTR, 0x11ced);
            if (doorState === 1 && !this.doorcheck) {
                EventHandler_1.bus.emit(Z64API.Z64.Z64Events.ON_ROOM_CHANGE_PRE, doorState);
                this.doorcheck = true;
            }
        });
        this.eventTicks.set('nightTick', () => {
            if (!this.isNight && this.save.world_night_flag) {
                this.isNight = true;
                EventHandler_1.bus.emit(Z64API.Z64.Z64Events.ON_NIGHT_TRANSITION, this.isNight);
            }
            else if (this.isNight && !this.save.world_night_flag) {
                this.isNight = false;
                EventHandler_1.bus.emit(Z64API.Z64.Z64Events.ON_DAY_TRANSITION, this.isNight);
            }
        });
        this.eventTicks.set('healthTick', () => {
            if (this.lastHealth !== this.save.health) {
                this.lastHealth = this.save.health;
                EventHandler_1.bus.emit(Z64API.Z64.Z64Events.ON_HEALTH_CHANGE, this.lastHealth);
            }
        });
        this.eventTicks.set('tunicTick', () => {
            if (this.lastTunic !== this.link.tunic) {
                this.lastTunic = this.link.tunic;
                EventHandler_1.bus.emit(Z64API.Z64.Z64Events.ON_TUNIC_CHANGE, this.lastTunic);
            }
        });
    }
    postinit() {
        this.global = new Z64CORE.OoT.GlobalContext(this.ModLoader);
        this.link = new Z64CORE.OoT.Link(this.ModLoader.emulator, this.ModLoader.math);
        this.save = new Z64CORE.OoT.SaveContext(this.ModLoader, this.ModLoader.logger, this);
        this.helper = new Z64CORE.OoT.OotHelper(this.save, this.global, this.link, this.ModLoader.emulator);
        this.ModLoader.payloadManager.registerPayloadType(new OverlayPayload_1.OverlayPayload('.ovl', this.ModLoader, this));
    }
    onTick(frame) {
        if (this.map_select_enabled) {
            this.mapSelectCode();
        }
        if (this.commandBuffer !== undefined)
            this.commandBuffer.onTick();
        //@ts-ignore
        if (this.actorManager !== undefined)
            this.actorManager.onTick();
        if (!this.helper.isTitleScreen()) {
            this.eventTicks.forEach((value, key) => {
                value();
            });
        }
    }
    onPostTick() {
        this.link.current_sound_id = 0;
    }
    onInject(evt) {
        /*         if (this.ModLoader.config.data["OcarinaofTime"]["skipN64Logo"]) {
                    this.ModLoader.logger.info("Skipping N64 logo screen...");
                    this.ModLoader.emulator.rdramWritePtr8(Z64_GLOBAL_PTR, 0x1E1, 0x1);
                } */
    }
    allZeroBufferCheck(buf) {
        for (let i = 0; i < buf.byteLength; i++) {
            if (buf[i] !== 0)
                return false;
        }
        return true;
    }
    onHeapSetup(evt) {
        // Scan memory.
        let start = 0x80400000;
        let scanSize = 0x1000000;
        let totalPossibleHeap = this.ModLoader.emulator.rdramReadBuffer(start, scanSize);
        while (!this.allZeroBufferCheck(totalPossibleHeap)) {
            start += (0x100000);
            scanSize -= (0x100000);
            totalPossibleHeap = this.ModLoader.emulator.rdramReadBuffer(start, scanSize);
        }
        let gfx_heap_start = start;
        let gfx_heap_size = scanSize;
        evt["gfx_heap_start"] = gfx_heap_start;
        evt["gfx_heap_size"] = gfx_heap_size;
        this.heap_start = 0x81000000;
        this.heap_size = 0x2E00000;
        this.ModLoader.logger.debug(`Oot Core Context: ${this.heap_start.toString(16)}. Size: 0x${this.heap_size.toString(16)}`);
        this.ModLoader.logger.debug(`Oot GFX Context: ${gfx_heap_start.toString(16)}. Size: 0x${gfx_heap_size.toString(16)}`);
    }
    onHeapReady(evt) {
        if (GameAliases_1.Z64_GAME !== OotAliases_1.OOTDBG_GAME) {
            this.commandBuffer = new Z64CORE.Z64.CommandBuffer(this.ModLoader, this.rom_header.revision, GameAliases_1.Z64_GAME, this);
            this.actorManager = new EventSystem_1.EventSystem(this.ModLoader, this, this.commandBuffer.cmdbuf);
        }
        let MessageContextPtr = this.ModLoader.emulator.rdramRead32(GameAliases_1.Z64_GLOBAL_PTR) + 0x0020D8;
        this.msgCtx = new MessageContext_1.default(this, this.ModLoader, MessageContextPtr);
    }
    mapSelectCode() {
        this.ModLoader.emulator.rdramWrite32(0x800F1434, 0x00B9E400);
        this.ModLoader.emulator.rdramWrite32(0x800F1438, 0x00BA1160);
        this.ModLoader.emulator.rdramWrite32(0x800F143C, 0x808009C0);
        this.ModLoader.emulator.rdramWrite32(0x800F1440, 0x80803720);
        this.ModLoader.emulator.rdramWrite32(0x800F1448, 0x80801C14);
        this.ModLoader.emulator.rdramWrite32(0x800F144C, 0x80801C08);
        if (this.ModLoader.emulator.rdramRead16(0x800F1430) === 0x803B) {
            this.ModLoader.emulator.rdramWrite8(0x8011B92F, 0);
        }
        if (this.ModLoader.emulator.rdramRead16(0x801C84B4) === 0x2030) {
            this.ModLoader.emulator.rdramWrite8(0x8011B92F, 0x0002);
            this.ModLoader.emulator.rdramWrite16(0x801DA2B4, 0x0EC0);
        }
    }
    toggleMapSelectKeybind() {
        this.map_select_enabled = true;
        return true;
    }
}
__decorate([
    (0, ModLoaderAPIInjector_1.ModLoaderAPIInject)()
], OcarinaofTime.prototype, "ModLoader", void 0);
__decorate([
    (0, EventHandler_1.EventHandler)(IModLoaderAPI_1.ModLoaderEvents.ON_SOFT_RESET_PRE)
], OcarinaofTime.prototype, "onReset1", null);
__decorate([
    (0, EventHandler_1.EventHandler)(IModLoaderAPI_1.ModLoaderEvents.ON_SOFT_RESET_POST)
], OcarinaofTime.prototype, "onReset2", null);
__decorate([
    (0, PluginLifecycle_1.onPostTick)()
], OcarinaofTime.prototype, "onPostTick", null);
__decorate([
    (0, EventHandler_1.EventHandler)(EventHandler_1.EventsClient.ON_INJECT_FINISHED)
], OcarinaofTime.prototype, "onInject", null);
__decorate([
    (0, EventHandler_1.EventHandler)(EventHandler_1.EventsClient.ON_HEAP_SETUP)
], OcarinaofTime.prototype, "onHeapSetup", null);
__decorate([
    (0, EventHandler_1.EventHandler)(EventHandler_1.EventsClient.ON_HEAP_READY)
], OcarinaofTime.prototype, "onHeapReady", null);
exports.OcarinaofTime = OcarinaofTime;
//# sourceMappingURL=OcarinaofTime.js.map