export var ServiceState;
(function (ServiceState) {
    /**
     * The service instance was created.
     * This is the starting point for any service.
     */
    ServiceState[ServiceState["Initialized"] = 0] = "Initialized";
    /**
     * After the `onCreate()` callback was called.
     */
    ServiceState[ServiceState["Created"] = 1] = "Created";
    /**
     * After the `onStart()` callback was called.
     */
    ServiceState[ServiceState["Started"] = 2] = "Started";
    /**
     * After the `onStop()` callback was called.
     */
    ServiceState[ServiceState["Stopped"] = 3] = "Stopped";
    /**
     * After the `onDestroy()` callback was called.
     */
    ServiceState[ServiceState["Destroyed"] = 4] = "Destroyed";
})(ServiceState || (ServiceState = {}));
export class Service extends EventTarget {
    /**
     * When set it will be used as the key to register and lookup a container.
     */
    static key;
    #state = ServiceState.Initialized;
    get currentState() {
        return this.#state;
    }
    /**
     * Start the service explicitly. It won't be called again until the service stops first.
     */
    async start() {
        if (this.#state !== ServiceState.Initialized) {
            return;
        }
        if (this.onCreate) {
            await this.onCreate();
            if (this.isDestroyed()) {
                return;
            }
        }
        this.#state = ServiceState.Created;
        this.dispatchEvent(new CustomEvent('service:created'));
        if (this.onStart) {
            await this.onStart();
            if (this.isDestroyed()) {
                return;
            }
        }
        this.#state = ServiceState.Started;
        this.dispatchEvent(new CustomEvent('service:started'));
    }
    /**
     * Stop the service explicitly. This allows the service to release resources, close connections, etc.
     */
    async stop() {
        if (![ServiceState.Started, ServiceState.Initialized, ServiceState.Created].includes(this.#state)) {
            return;
        }
        this.#state = ServiceState.Stopped;
        if (this.onStop) {
            await this.onStop();
        }
        this.dispatchEvent(new CustomEvent('service:stopped'));
    }
    async destroy() {
        if (this.#state === ServiceState.Destroyed) {
            return;
        }
        this.#state = ServiceState.Destroyed;
        if (this.onDestroy) {
            await this.onDestroy();
        }
        this.dispatchEvent(new CustomEvent('service:destroyed'));
    }
    isDestroyed() {
        return this.#state === ServiceState.Destroyed;
    }
}
//# sourceMappingURL=Service.js.map