/*
 * ******************************************************************
 * Copyright (c) 2024 Broadcom. All Rights Reserved.
 * Broadcom Confidential. The term "Broadcom" refers to Broadcom Inc.
 * and/or its subsidiaries.
 * ******************************************************************
 */
import { Injectable } from "@angular/core";
import { BehaviorSubject, filter, interval, map, take } from "rxjs";
import { ALL_EXTENSIONS_LOADED, HAS_EXTENSIONS, HYPER_PLUGIN_STATE, HyperPluginState, REGISTERED_EXTENSION_POINTS } from "../extensibility-framework/common/extensibility/extensibility.model";

@Injectable()
export class GeneralExtensibilityService {
    private extensionsLoadedSbj = new BehaviorSubject<boolean>(false);
    public allExtensionsLoaded = this.extensionsLoadedSbj.asObservable();

    private hasExtensionsSbj = new BehaviorSubject<boolean>(null);
    public hasExtensions = this.hasExtensionsSbj.asObservable();

    constructor() {
        const hyperPluginState: HyperPluginState = window[HYPER_PLUGIN_STATE];

        if (hyperPluginState[ALL_EXTENSIONS_LOADED]) {
            this.setAllExtensionsLoaded();
        }

        interval(1000).pipe(
            filter(() => {
                return hyperPluginState[ALL_EXTENSIONS_LOADED];
            }),
            take(1),
            map(() => {
                this.setAllExtensionsLoaded();
            })
        ).subscribe();

        interval(1000).pipe(
            filter(() => {
                /**
                 * The initial value of `HAS_EXTENSIONS` must not be boolean
                 * so we can accuretly determine of there are extensions available.
                 */
                return hyperPluginState[HAS_EXTENSIONS] !== null && hyperPluginState[HAS_EXTENSIONS] !== undefined;
            }),
            take(1),
            map(() => {
                this.hasExtensionsSbj.next(hyperPluginState[HAS_EXTENSIONS]);
            }),
        ).subscribe();
    }

    setAllExtensionsLoaded() {
        this.extensionsLoadedSbj.next(true);
    }
}