"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;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.MajorasMask = void 0;
const PluginLifecycle_1 = require("modloader64_api/PluginLifecycle");
const ModLoaderAPIInjector_1 = require("modloader64_api/ModLoaderAPIInjector");
const IModLoaderAPI_1 = require("modloader64_api/IModLoaderAPI");
const EventHandler_1 = require("modloader64_api/EventHandler");
const Z64API = __importStar(require("../API/imports"));
const Z64CORE = __importStar(require("./importsZ64"));
const Z64Lib_1 = require("./Z64Lib");
const OverlayPayload_1 = require("./OverlayPayload");
const EventSystem_1 = require("./Common/CommandBuffer/EventSystem");
const imports_1 = require("./Common/imports");
class MajorasMask {
    header = [Z64Lib_1.ROM_REGIONS.NTSC_MM];
    ModLoader = {};
    eventTicks = new Map();
    link;
    save;
    global;
    helper;
    commandBuffer;
    photo;
    skull;
    stray;
    // Client side variables
    isSaveLoaded = false;
    isPaused = false;
    last_known_scene = -1;
    last_known_room = -1;
    doorcheck = false;
    touching_loading_zone = false;
    frame_count_reset_scene = -1;
    last_known_age;
    log;
    actorManager;
    payloads = new Array();
    inventory_cache = Buffer.alloc(0x18, 0xff);
    id = [4];
    param = [0];
    rom_header;
    heap_start = 0;
    heap_size = 0;
    sceneLockout = false;
    preinit() {
    }
    onReset1(evt) {
        this.isSaveLoaded = false;
    }
    onReset2(evt) {
        this.isSaveLoaded = false;
    }
    init() {
        this.eventTicks.set('waitingForSaveload', () => {
            if (!this.isSaveLoaded && this.helper.isSceneNumberValid() && !this.helper.isTitleScreen()) {
                this.isSaveLoaded = true;
                EventHandler_1.bus.emit(Z64API.Z64.Z64Events.ON_SAVE_LOADED, {});
            }
        });
    }
    postinit() {
        this.global = new Z64CORE.MM.GlobalContext(this.ModLoader);
        this.link = new Z64CORE.MM.Link(this.ModLoader.emulator);
        this.save = new Z64CORE.MM.SaveContext(this.ModLoader.emulator, this.ModLoader.logger, this);
        this.helper = new Z64CORE.MM.MMHelper(this.save, this.global, this.link, this.ModLoader.emulator);
        this.ModLoader.payloadManager.registerPayloadType(new OverlayPayload_1.OverlayPayload('.ovl', this.ModLoader, this));
    }
    onTick() {
        if (this.commandBuffer !== undefined) {
            this.commandBuffer.onTick();
        }
        if (this.helper.isTitleScreen() || !this.helper.isSceneNumberValid())
            return;
        //@ts-ignore
        if (this.actorManager !== undefined)
            this.actorManager.onTick();
        // Loading zone check
        if (this.helper.isLinkEnteringLoadingZone() && !this.touching_loading_zone) {
            EventHandler_1.bus.emit(Z64API.Z64.Z64Events.ON_LOADING_ZONE, {});
            this.touching_loading_zone = true;
        }
        // Scene change check
        if (this.global.transitionState === 236 /* TransitionState.FADING_IN */ &&
            !this.sceneLockout) {
            this.last_known_scene = this.global.scene;
            EventHandler_1.bus.emit(Z64API.Z64.Z64Events.ON_SCENE_CHANGE, this.last_known_scene);
            this.touching_loading_zone = false;
            this.sceneLockout = true;
            this.ModLoader.utils.setTimeoutFrames(() => {
                this.sceneLockout = false;
            }, 20);
        }
        // Age check
        if (this.save.form !== this.last_known_age) {
            this.last_known_age = this.save.form;
            EventHandler_1.bus.emit(Z64API.Z64.Z64Events.ON_AGE_CHANGE, this.last_known_age);
        }
        // UnPause Check
        if (this.helper.isPaused()) {
            this.isPaused = true;
        }
        else if (!this.helper.isPaused() && this.isPaused) {
            this.isPaused = false;
            EventHandler_1.bus.emit(Z64API.Z64.Z64Events.ON_UNPAUSE);
        }
        this.eventTicks.forEach((value, key) => {
            value();
        });
    }
    onViUpdate() {
        /*         this.ModLoader.ImGui.begin("Dood spawner")
                {
                    this.ModLoader.ImGui.inputInt("Id", this.id, undefined, undefined, InputTextFlags.CharsHexadecimal)
                    this.ModLoader.ImGui.inputInt("Param", this.param, undefined, undefined, InputTextFlags.CharsHexadecimal)
                    if (this.ModLoader.ImGui.button("Spawn dood")) {
                        if (this.commandBuffer !== undefined) {
                            this.commandBuffer.spawnActor(this.id[0], this.param[0], new Vector3(), this.link.position.getVec3())
                        }
                    }
                }
                this.ModLoader.ImGui.end() */
    }
    onPostTick() {
        this.link.current_sound_id = 0;
    }
    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(`MM Core Context: ${this.heap_start.toString(16)}. Size: 0x${this.heap_size.toString(16)}`);
        this.ModLoader.logger.debug(`MM GFX Context: ${gfx_heap_start.toString(16)}. Size: 0x${gfx_heap_size.toString(16)}`);
    }
    onHeapReady(evt) {
        this.commandBuffer = new Z64CORE.Z64.CommandBuffer(this.ModLoader, this.rom_header.revision, imports_1.Z64_GAME, this);
        this.actorManager = new EventSystem_1.EventSystem(this.ModLoader, this, this.commandBuffer.cmdbuf);
    }
    toggleMapSelectKeybind() {
        return false;
    }
}
__decorate([
    (0, ModLoaderAPIInjector_1.ModLoaderAPIInject)()
], MajorasMask.prototype, "ModLoader", void 0);
__decorate([
    (0, PluginLifecycle_1.Preinit)()
], MajorasMask.prototype, "preinit", null);
__decorate([
    (0, EventHandler_1.EventHandler)(IModLoaderAPI_1.ModLoaderEvents.ON_SOFT_RESET_PRE)
], MajorasMask.prototype, "onReset1", null);
__decorate([
    (0, EventHandler_1.EventHandler)(IModLoaderAPI_1.ModLoaderEvents.ON_SOFT_RESET_POST)
], MajorasMask.prototype, "onReset2", null);
__decorate([
    (0, PluginLifecycle_1.Init)()
], MajorasMask.prototype, "init", null);
__decorate([
    (0, PluginLifecycle_1.Postinit)()
], MajorasMask.prototype, "postinit", null);
__decorate([
    (0, PluginLifecycle_1.onTick)()
], MajorasMask.prototype, "onTick", null);
__decorate([
    (0, PluginLifecycle_1.onViUpdate)()
], MajorasMask.prototype, "onViUpdate", null);
__decorate([
    (0, PluginLifecycle_1.onPostTick)()
], MajorasMask.prototype, "onPostTick", null);
__decorate([
    (0, EventHandler_1.EventHandler)(EventHandler_1.EventsClient.ON_HEAP_SETUP)
], MajorasMask.prototype, "onHeapSetup", null);
__decorate([
    (0, EventHandler_1.EventHandler)(EventHandler_1.EventsClient.ON_HEAP_READY)
], MajorasMask.prototype, "onHeapReady", null);
exports.MajorasMask = MajorasMask;
//# sourceMappingURL=MajorasMask.js.map