import { Translator } from "../i18n/api"; export type Speaker = { id: "host" | "guest", language : string, } export class Message { public translation? : string; public onTextUpdate?: (message: Message) => void; public onTextDone?: (message: Message) => Promise; public onTranslationDone?: (message: Message) => void; constructor (public conversation : Conversation, public speaker : Speaker, public text? : string) {} get otherSpeaker() { return this.speaker.id === this.conversation.host.id ? this.conversation.guest : this.conversation.host } get otherLanguage() { return this.otherSpeaker.language } public async translate() { const translator = this.conversation.translator if (!this.text) throw new Error("No text") console.log("Translating from %s -> %s", this.speaker.language, this.otherSpeaker.language); this.translation = await translator.translate(this.text, this.otherLanguage); this.onTranslationDone && this.onTranslationDone(this) } } export class Conversation extends Array { public onAddMessage? : (conversation : Conversation) => any; public onTranslationDone? : (conversation : Conversation) => any; constructor ( public translator : Translator, public host : Speaker, public guest : Speaker, ) { super(); } public addMessage(speaker : Speaker, text? : string) { this.push(new Message(this, speaker, text)); } public async translateMessage(i : number) { if (!this[i]) throw new Error(`${i} is not a valid message number`); console.log(`Translating sentence to %s: %s`, this[i].otherLanguage, this[i].text) await this[i].translate(); } get lastMessage() { return this[this.length-1] } public async translateLast() { return await this.translateMessage(this.length-1); } }