/*
 * Copyright 2020 VMware, Inc. All rights reserved. VMware Confidential
 */

import { Injectable } from "@angular/core";
import { Store } from "@ngrx/store";
import { TranslationService } from "@vcd/i18n";
import { Observable } from "rxjs";
import { filter, map } from "rxjs/operators";
import { CodeBasedExtensionNavRegistration, TextBasedExtensionNavRegistration } from "../../models/extension";
import { AppState } from "../../state/app.state";

/**
 * A service that knows how to return all the top-level plugin routes that are in the Store.
 */
@Injectable({
    providedIn: "root",
})
export class PluginsNavigationRoutesService {
    private extensionNavRegistrations: Observable<TextBasedExtensionNavRegistration[]>;

    constructor(store: Store<AppState>, translationService: TranslationService) {
        this.extensionNavRegistrations = store.select("appExtensions", "navRegistrations").pipe(
            filter(Boolean),
            map((registrations) =>
                registrations.map((plugin) => {
                    (plugin as TextBasedExtensionNavRegistration).nameText = (plugin as CodeBasedExtensionNavRegistration)
                        .nameCode
                        ? translationService.translate((plugin as CodeBasedExtensionNavRegistration).nameCode)
                        : (plugin as TextBasedExtensionNavRegistration).nameText;

                    (plugin as TextBasedExtensionNavRegistration).descriptionText = (plugin as CodeBasedExtensionNavRegistration)
                        .descriptionCode
                        ? translationService.translate((plugin as CodeBasedExtensionNavRegistration).descriptionCode)
                        : (plugin as TextBasedExtensionNavRegistration).descriptionText;

                    return plugin as TextBasedExtensionNavRegistration;
                })
            )
        );
    }

    getExtensionNavRegistrations(): Observable<TextBasedExtensionNavRegistration[]> {
        return this.extensionNavRegistrations;
    }
}
