import Locale from "../Locale";

import englishErrors from "../translations/beinformed_error_messages_en.nl.js";
import { IllegalStateException } from "../../exceptions";
import { setSetting } from "../../constants";

global.console = {
  warn: jest.fn(),
  debug: jest.fn(),
};

jest.mock(
  "../translations/layout_en.nl.json",
  () => ({
    testMessage: "testMessage",
    messageWithParams: "Param 1: {param1}, Param 2: {param2}",
    messageWithJavaParams: "Param 1: ${param1}, Param 2: ${param2}", // NOSONAR
  }),
  { virtual: true },
);

describe("locale", () => {
  it("should be able to give back the native name of a locale", () => {
    const locale = new Locale({
      code: "en-US",
      messages: {},
      errors: englishErrors,
    });

    expect(locale.code).toBe("en-US");
    expect(locale.nativeName).toBe("English (US)");

    expect(locale.getMessage()).toBe("[message: id or defaultMessage missing]");
    expect(locale.getMessage("testMessage")).toBe("testMessage");

    locale.update({
      testMessage: "Updated message",
    });

    expect(locale.getMessage("testMessage")).toBe("Updated message");
  });

  it("can handle languages without iso-639-2 code", () => {
    const locale = new Locale({
      code: "pap",
      nativeName: "Papiamento",
      messages: {
        descr: "Papiamento",
      },
      errors: {},
    });

    expect(locale.code).toBe("pap");
    expect(locale.nativeName).toBe("Papiamento");
  });

  it("throws on non exising locale", () => {
    const locale = new Locale({
      code: "NONEXISTING",
    });

    expect(() => {
      locale.nativeName;
    }).toThrow(IllegalStateException);
  });

  it("updates be informed message export to format-message formatted messages", () => {
    const messages = {
      code: "Parameter '${parameter}' is niet toegestaan",
    };

    const locale = new Locale({
      code: "CUSTOM",
      messages,
    });

    expect(locale.fixPlaceHoldersInObject(messages)).toStrictEqual({
      code: "Parameter ''{parameter}'' is niet toegestaan",
    });

    expect(
      locale.getMessage("code", "", {
        parameter: "parameterName",
      }),
    ).toBe("Parameter 'parameterName' is niet toegestaan");
  });

  it("handle non existing messages", () => {
    const locale = new Locale({ code: "de" });

    const msg = locale.getMessage("non-existing");
    expect(msg).toBe("non-existing");
    expect(global.console.debug).toHaveBeenCalledWith(
      "Message with id non-existing not found for locale de in layout translations",
    );

    const msgWithDefault = locale.getMessage("non-existing", "Default");
    expect(msgWithDefault).toBe("Default");

    global.console.warn.mockClear();

    setSetting("DEBUG_I18N_MESSAGE_NOT_FOUND", false);

    const msgNoWarn = locale.getMessage("non-existing");
    expect(msgNoWarn).toBe("non-existing");
    expect(global.console.warn).not.toHaveBeenCalled();
  });
});
