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

import { Injectable } from "@angular/core";
import { MessageFormatTranslationService, TranslationService, TranslationSet } from "@vcd/i18n";
import { ActionItem } from "@vcd/ui-components";
import { RESOURCES_ROUTE } from "../../app/plugin-container/plugin-container.module";
import { ExtensionPointManifest } from "./extensibility.model";
import { APPLICATIONS_TYPE } from "./applications/applications.extension-point";
import { DATACENTER_OVERVIEW_TYPES } from "./datacenter-overview/datacenter-overview.extension-point";

@Injectable({
    providedIn: "root",
})
export class PluginUtilService {
    constructor(private translationService: TranslationService) {}

    public buildStartResourceSegment(extensionType: string): string {
        let resourcePath: string;

        if (extensionType === APPLICATIONS_TYPE) {
            resourcePath = "applications";
        } else if (DATACENTER_OVERVIEW_TYPES.indexOf(extensionType) !== -1) {
            resourcePath = "vdcs";
        }

        if (resourcePath) {
            return `/${resourcePath}/${RESOURCES_ROUTE}`;
        }

        return `/${RESOURCES_ROUTE}`;
    }

    public buildResourcePath(extensionPoint: ExtensionPointManifest): string {
        if (extensionPoint) {
            return `${this.buildStartResourceSegment(extensionPoint.type)}/${extensionPoint.urn}`;
        }

        throw new Error("No extension point provided.");
    }

    public translate(text: string, translations: TranslationSet): string {
        if (!this.isExtensionTranslationPlaceholder(text)) {
            return text;
        }

        const translationString = text.split("%").filter(Boolean)[0];

        if (translations) {
            const translationService = new MessageFormatTranslationService(window.navigator.language, "en");
            translationService.registerTranslations(translations);
            return translationService.translate(translationString);
        }

        return this.translationService.translate(translationString);
    }

    /**
     * Takes non-extension actions, extension actions as input and inserts the extension actions at an index close
     * to middle of the non-extension actions list. It finds the index of the closest separator from the middle and
     * inserts the extension actions after that index to avoid being inserted into an existing actions group
     */
    public insertExtensionActions(
        vcdActions: ActionItem<unknown, unknown>[],
        extensionActions
    ): ActionItem<unknown, unknown>[] {
        if (!extensionActions?.length) {
            return vcdActions;
        }
        const vcdActionsCopy = [...vcdActions];
        let extensionActionsCopy = [...extensionActions];
        const extensionActionsInsertIndex = this.getExtensionActionsInsertIndex(vcdActionsCopy);
        if (vcdActionsCopy[extensionActionsInsertIndex]?.isSeparator) {
            extensionActionsCopy = [{ isSeparator: true }, ...extensionActionsCopy];
        } else {
            extensionActionsCopy = [{ isSeparator: true }, ...extensionActionsCopy, { isSeparator: true }];
        }
        vcdActionsCopy.splice(extensionActionsInsertIndex, 0, ...extensionActionsCopy);
        return vcdActionsCopy;
    }

    private getExtensionActionsInsertIndex(vcdActions: ActionItem<unknown, unknown>[]): number {
        const actionsMidIndex = vcdActions.length % 2 == 0 ? vcdActions.length / 2 : Math.floor(vcdActions.length / 2);
        // Check below the mid point
        let separatorIndex: number;
        separatorIndex = vcdActions.slice(actionsMidIndex).findIndex((action) => action.isSeparator);
        if (separatorIndex > -1) {
            return actionsMidIndex + separatorIndex;
        }
        // Check above the mid point
        separatorIndex = vcdActions
            .slice(0, actionsMidIndex)
            .reverse()
            .findIndex((action) => action.isSeparator);
        if (separatorIndex > -1) {
            return vcdActions.slice(0, actionsMidIndex).length - 1 - separatorIndex;
        }
        // Stick in the middle
        return actionsMidIndex;
    }

    private isExtensionTranslationPlaceholder(text: string): boolean {
        return text.startsWith("%") && text.endsWith("%");
    }
}
