/*
 * Copyright 2017-2022 VMware, Inc. All rights reserved. VMware Confidential
 */

import { HttpClient } from "@angular/common/http";
import { Injectable } from "@angular/core";
import { Observable, of } from "rxjs";
import { catchError, map, tap } from "rxjs/operators";
import { EXTENSION_MANIFEST_VERSIONS } from "../../extensibility.model";
import { ExtensionLoaderStep, ExternalExtensionLoaderState } from "../extension-loader.model";
import { ExternalExtensionLoaderErrorObservable } from "./external-extension-loader-error";
import { TranslationSet } from "@vcd/i18n";

export const PLUGIN_I18N_URL = "/i18n.json";

@Injectable()
export class LoadExternalExtensionI18nStep implements ExtensionLoaderStep<ExternalExtensionLoaderState> {
    constructor(private http: HttpClient) {}

    /**
     * Load an extension's i18n data from {extensionRoot}/i18n.json.
     * State inputs: spec, manifest
     * State outputs: translations
     */
    public perform(state: ExternalExtensionLoaderState): Observable<ExternalExtensionLoaderState> {
        try {
            if (state.manifest.manifestVersion >= EXTENSION_MANIFEST_VERSIONS["2.0.0"]) {
                if (!state.manifest.locales) {
                    console.error(`Please provide localization in the manifest of ${state.manifest.name}`);
                }

                return of({ ...state, translations: { ...state.manifest.locales } });
            }

            const i18nJsonFile = state.spec.resourcePath + PLUGIN_I18N_URL;
            console.log(`[${state.spec.id} (${state.manifest.name})] Loading i18n from: ${i18nJsonFile}`);
            return this.http.get<TranslationSet>(i18nJsonFile).pipe(
                tap(() => console.log(`[${state.spec.id} (${state.manifest.name})] I18n loaded`)),

                map((translations) => ({ ...state, translations })),
                catchError((err, caught) => {
                    console.info(`[${state?.spec?.id} (${state?.manifest?.name})] Could not load i18n`, err);
                    return of({ ...state, translations: {} });
                })
            );
        } catch (err) {
            console.info(`[${state?.spec?.id} (${state?.manifest?.name})] Could not load i18n`, err);
            return new ExternalExtensionLoaderErrorObservable();
        }
    }
}
