import type { EventKey, SurveyEventKey, WidgetCallbacks, WidgetResponse } from "../../domain"; import type { WidgetStateManager } from "../WidgetStateManager"; import { handleFormClose, handleFormError, handleFormPageChanged, handleQuestionAnswered, handleFormCompleted, handleFormPartialCompleted, handleFormResize } from "./EventHandlers"; export class EventHandlerFactory { private readonly surveyToFormMapping: Record = { closeSoluCXWidget: "FORM_CLOSE", dismissSoluCXWidget: "FORM_CLOSE", completeSoluCXWidget: "FORM_COMPLETED", partialSoluCXWidget: "FORM_PARTIALCOMPLETED", resizeSoluCXWidget: "FORM_RESIZE", errorSoluCXWidget: "FORM_ERROR", }; constructor( private hide: () => void, private resize: (height: string) => void, private userId: string, private transactionId?: string, private callbacks?: WidgetCallbacks, private stateManager?: WidgetStateManager, ) {} private parse(message: string): { key: string; value: string } { const separatorIndex = message.indexOf("-"); if (separatorIndex === -1) return { key: message, value: "" }; return { key: message.slice(0, separatorIndex), value: message.slice(separatorIndex + 1), }; } private mapSurveyKeyToFormKey(surveyKey: SurveyEventKey): EventKey { return this.surveyToFormMapping[surveyKey] as EventKey; } private normalizeKey(key: string, isForm: boolean): EventKey { if (isForm) { return key as EventKey; } return this.mapSurveyKeyToFormKey(key as SurveyEventKey); } async processMessage(message: string, isForm: boolean): Promise { const parsed = this.parse(message); const eventKey = this.normalizeKey(parsed.key, isForm); return this.handle(eventKey, parsed.value); } private async handle(eventKey: EventKey, value: string): Promise { switch (eventKey) { case "FORM_CLOSE": return handleFormClose(this.hide, this.stateManager, this.callbacks); case "FORM_ERROR": return handleFormError(value, this.hide, this.callbacks); case "FORM_PAGECHANGED": return handleFormPageChanged(value, this.callbacks); case "QUESTION_ANSWERED": return handleQuestionAnswered(this.stateManager, this.callbacks); case "FORM_COMPLETED": return handleFormCompleted(this.userId, this.transactionId, this.stateManager, this.callbacks); case "FORM_PARTIALCOMPLETED": return handleFormPartialCompleted(this.userId, this.transactionId, this.stateManager, this.callbacks); case "FORM_RESIZE": return handleFormResize(value, this.resize, this.callbacks); default: return { status: "error", message: "Unknown event" }; } } }