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 EntityPermissionsEntity_Server_1;
import { RegisterClass } from '@memberjunction/global';
import { BaseEntity } from '@memberjunction/core';
import { EntityPermissionEntity } from '@memberjunction/core-entities';
import axios from 'axios';
import { ___codeGenAPIPort, ___codeGenAPISubmissionDelay, ___codeGenAPIURL } from '../config.js';
/**
 * Server-side only class that extends the entity permissions object to watch for changes to entity permissions, build a queue of entities that have been changed, and then from time to time, submit
 * them to an API server that will execute the underlying permission changes at the database level.
 *
 * This class is within the memberjunction/server package because it is closely coupled to other aspects of what
 * happens in the server. That's why it is not in the core-entities-server package.
 */
let EntityPermissionsEntity_Server = class EntityPermissionsEntity_Server extends EntityPermissionEntity {
    static { EntityPermissionsEntity_Server_1 = this; }
    static { this._entityIDQueue = []; }
    static { this._lastModifiedTime = null; }
    static { this._submissionTimer = null; }
    static { this._submissionDelay = ___codeGenAPISubmissionDelay; }
    static { this._baseURL = ___codeGenAPIURL; }
    static { this._port = ___codeGenAPIPort; }
    static { this._apiEndpoint = '/api/entity-permissions'; }
    // Method to construct the full URL dynamically
    static getSubmissionURL() {
        return `${this._baseURL}:${this._port}${this._apiEndpoint}`;
    }
    static get EntityIDQueue() {
        return this._entityIDQueue;
    }
    static ClearQueue() {
        this._entityIDQueue = [];
        this._submissionTimer = null;
    }
    static AddToQueue(entityID) {
        if (this._entityIDQueue.indexOf(entityID) === -1)
            this._entityIDQueue.push(entityID);
        this._lastModifiedTime = new Date();
        this.CheckStartSubmissionTimer();
    }
    static CheckStartSubmissionTimer() {
        if (this._submissionTimer === null) {
            this.StartSubmissionTimer();
        }
        else {
            // we need to cancel the existing timer and start a new one
            clearTimeout(this._submissionTimer);
            this.StartSubmissionTimer();
        }
    }
    static StartSubmissionTimer() {
        this._submissionTimer = setTimeout(() => {
            this.SubmitQueue();
        }, this._submissionDelay);
    }
    static async SubmitQueue() {
        this._lastModifiedTime = null;
        // now, use Axios to submit the queue to the API server
        // Check if there's anything to submit
        if (this._entityIDQueue.length > 0) {
            try {
                // Use Axios to submit the queue to the API server
                const response = await axios.post(this.getSubmissionURL(), {
                    entityIDArray: this._entityIDQueue,
                });
                // Check the Axios response code implicitly and API response explicitly
                if (response.status === 200 && response.data.status === 'ok') {
                    console.log('Queue submitted successfully.');
                    // now, clear the queue and timer
                    this.ClearQueue();
                }
                else {
                    // Handle API indicating a failure
                    console.error('Failed to submit queue:', response.data.errorMessage || 'Unknown error');
                }
            }
            catch (error) {
                // Handle errors here
                console.error('Failed to submit queue:', error);
                // Consider re-trying or logging the error based on your requirements
            }
        }
        else {
            console.log('No entities to submit.');
        }
    }
    Save(options) {
        // simply queue up the entity ID
        if (this.Dirty || options?.IgnoreDirtyState)
            EntityPermissionsEntity_Server_1.AddToQueue(this.EntityID);
        return super.Save(options);
    }
    async Delete(options) {
        const success = await super.Delete(options);
        // simply queue up the entity ID if the delete worked
        if (success)
            EntityPermissionsEntity_Server_1.AddToQueue(this.EntityID);
        return success;
    }
};
EntityPermissionsEntity_Server = EntityPermissionsEntity_Server_1 = __decorate([
    RegisterClass(BaseEntity, 'Entity Permissions')
], EntityPermissionsEntity_Server);
export { EntityPermissionsEntity_Server };
//# sourceMappingURL=entityPermissions.server.js.map