import * as mc from "@minecraft/server";
import { DataBase } from "./database";
import { ActorComponent } from "../npc_system";
export class DatabaseComponent extends ActorComponent {
    constructor() {
        super(...arguments);
        this.onKilledBinding = this.onKilled.bind(this);
        this.onDataChangedBinding = this.onDataChanged.bind(this);
    }
    get Database() {
        if (this.database)
            return this.database;
        if (this.options.databaseKey.type === "owner_id") {
            const tameable = this.actor.getComponent("tameable");
            if (tameable && tameable.tamedToPlayerId) {
                this.database = DataBase.getDatabase(tameable.tamedToPlayerId);
                return this.database;
            }
        }
        else {
            this.database = DataBase.getDatabase(this.options.databaseKey.value);
            return this.database;
        }
    }
    get Table() {
        var _a;
        return (_a = this.Database) === null || _a === void 0 ? void 0 : _a.getTableFromEntryKey(this.actor.id);
    }
    onComponentAdded() {
        var _a, _b, _c;
        mc.world.afterEvents.entityDie.subscribe(this.onKilledBinding, { entities: [this.actor.UnsafeEntity] });
        this.actor.subscribe("data_changed", this.onDataChangedBinding);
        if (this.options.addToTableDefault && !((_a = this.Database) === null || _a === void 0 ? void 0 : _a.hasEntry(this.actor.id))) {
            (_c = (_b = this.Database) === null || _b === void 0 ? void 0 : _b.getTable(this.options.addToTableDefault)) === null || _c === void 0 ? void 0 : _c.setEntry(this.actor.id, this.actor.getDataEntry());
        }
    }
    onComponentRemoved() {
        mc.world.afterEvents.entityDie.unsubscribe(this.onKilledBinding);
        this.actor.unsubscribe("data_changed", this.onDataChangedBinding);
    }
    onDataChanged() {
        var _a, _b;
        (_b = (_a = this.Database) === null || _a === void 0 ? void 0 : _a.getTableFromEntryKey(this.actor.id)) === null || _b === void 0 ? void 0 : _b.setEntry(this.actor.id, this.actor.getDataEntry());
    }
    onKilled(event) {
        var _a;
        (_a = this.Database) === null || _a === void 0 ? void 0 : _a.clearEntryFromAllTables(this.actor.id);
    }
}
