From e089718203007b68b96489a4ca53361d8be49817 Mon Sep 17 00:00:00 2001
From: Ruben Bimberg <ruben.bimberg@mni.thm.de>
Date: Tue, 5 Oct 2021 14:48:50 +0200
Subject: [PATCH] Implement new deepl behavior

---
 .../comment-settings.component.ts             |  4 +-
 .../create-comment.component.html             |  3 +-
 .../create-comment.component.ts               | 81 +++++++++++++------
 .../deep-ldialog/deep-ldialog.component.ts    |  6 +-
 .../spacy-dialog/spacy-dialog.component.ts    | 11 +++
 .../write-comment.component.html              |  2 +-
 .../write-comment/write-comment.component.ts  | 40 +++++----
 7 files changed, 101 insertions(+), 46 deletions(-)

diff --git a/src/app/components/creator/_dialogs/comment-settings/comment-settings.component.ts b/src/app/components/creator/_dialogs/comment-settings/comment-settings.component.ts
index 23ee53f0d..501cb1d2b 100644
--- a/src/app/components/creator/_dialogs/comment-settings/comment-settings.component.ts
+++ b/src/app/components/creator/_dialogs/comment-settings/comment-settings.component.ts
@@ -9,10 +9,8 @@ import { CommentService } from '../../../../services/http/comment.service';
 import { BonusTokenService } from '../../../../services/http/bonus-token.service';
 import { DeleteCommentsComponent } from '../delete-comments/delete-comments.component';
 import { Room } from '../../../../models/room';
-import { CommentBonusTokenMixin } from '../../../../models/comment-bonus-token-mixin';
 import { CommentSettings } from '../../../../models/comment-settings';
 import { CommentSettingsDialog } from '../../../../models/comment-settings-dialog';
-import { ExportCsv } from '../../../../models/export-csv';
 import { Export } from '../../../../models/export';
 
 @Component({
@@ -47,7 +45,7 @@ export class CommentSettingsComponent implements OnInit {
   ngOnInit() {
     if (this.editRoom.threshold !== null) {
       this.commentThreshold = this.editRoom.threshold;
-      this.settingThreshold = true;
+      this.settingThreshold = !!this.editRoom.threshold;
     }
     this.tags = [];
     this.enableCommentModeration = this.editRoom.moderated;
diff --git a/src/app/components/shared/_dialogs/create-comment/create-comment.component.html b/src/app/components/shared/_dialogs/create-comment/create-comment.component.html
index 1c18a3975..5425e1e0a 100644
--- a/src/app/components/shared/_dialogs/create-comment/create-comment.component.html
+++ b/src/app/components/shared/_dialogs/create-comment/create-comment.component.html
@@ -1,7 +1,8 @@
 <ars-row ars-flex-box>
   <app-write-comment [confirmLabel]="'send'"
                      [isQuestionerNameEnabled]="true"
-                     [onSubmit]="this.closeDialog.bind(this)"
+                     [onSubmit]="this.forwardComment.bind(this)"
+                     [onDeeplSubmit]="this.closeDialog.bind(this)"
                      [onClose]="this.onNoClick.bind(this)"
                      [isSpinning]="isSendingToSpacy"
                      [tags]="tags"
diff --git a/src/app/components/shared/_dialogs/create-comment/create-comment.component.ts b/src/app/components/shared/_dialogs/create-comment/create-comment.component.ts
index 20b6adde4..88a701eb3 100644
--- a/src/app/components/shared/_dialogs/create-comment/create-comment.component.ts
+++ b/src/app/components/shared/_dialogs/create-comment/create-comment.component.ts
@@ -6,9 +6,11 @@ import { TranslateService } from '@ngx-translate/core';
 import { User } from '../../../../models/user';
 import { EventService } from '../../../../services/util/event.service';
 import { SpacyDialogComponent } from '../spacy-dialog/spacy-dialog.component';
-import { LanguagetoolService, Language } from '../../../../services/http/languagetool.service';
+import { LanguagetoolService, Language, LanguagetoolResult } from '../../../../services/http/languagetool.service';
 import { CreateCommentKeywords } from '../../../../utils/create-comment-keywords';
 import { WriteCommentComponent } from '../../write-comment/write-comment.component';
+import { DeepLDialogComponent } from '../deep-ldialog/deep-ldialog.component';
+import { DeepLService, SourceLang, TargetLang } from '../../../../services/http/deep-l.service';
 
 @Component({
   selector: 'app-submit-comment',
@@ -30,6 +32,7 @@ export class CreateCommentComponent implements OnInit {
     private translateService: TranslateService,
     public dialog: MatDialog,
     public languagetoolService: LanguagetoolService,
+    private deeplService: DeepLService,
     public eventService: EventService,
     @Inject(MAT_DIALOG_DATA) public data: any) {
   }
@@ -43,7 +46,15 @@ export class CreateCommentComponent implements OnInit {
     this.dialogRef.close();
   }
 
+  forwardComment(body: string, text: string, tag: string, name: string, verifiedWithoutDeepl: boolean) {
+    this.createComment(body, text, tag, name, !verifiedWithoutDeepl);
+  }
+
   closeDialog(body: string, text: string, tag: string, name: string) {
+    this.createComment(body, text, tag, name);
+  }
+
+  createComment(body: string, text: string, tag: string, name: string, forward = false) {
     const comment = new Comment();
     comment.roomId = localStorage.getItem(`roomId`);
     comment.body = body;
@@ -52,34 +63,18 @@ export class CreateCommentComponent implements OnInit {
     comment.tag = tag;
     comment.questionerName = name;
     this.isSendingToSpacy = true;
-    this.openSpacyDialog(comment, text);
+    this.openSpacyDialog(comment, text, forward);
   }
 
-  openSpacyDialog(comment: Comment, rawText: string): void {
+  openSpacyDialog(comment: Comment, rawText: string, forward: boolean): void {
     CreateCommentKeywords.isSpellingAcceptable(this.languagetoolService, rawText, this.commentComponent.selectedLang)
       .subscribe((result) => {
         if (result.isAcceptable) {
-          const commentLang = this.languagetoolService.mapLanguageToSpacyModel(result.result.language.code as Language);
-          const selectedLangExtend = this.commentComponent.selectedLang[2] === '-' ?
-            this.commentComponent.selectedLang.substr(0, 2) : this.commentComponent.selectedLang;
-          // Store language if it was auto-detected
-          if (this.commentComponent.selectedLang === 'auto') {
-            comment.language = Comment.mapModelToLanguage(commentLang);
-          } else if (CommentLanguage[selectedLangExtend]) {
-            comment.language = CommentLanguage[selectedLangExtend];
+          if (forward) {
+            this.callDeepL(comment, result.text, result.result);
+          } else {
+            this.callSpacy(comment, result.text, result.result);
           }
-          const dialogRef = this.dialog.open(SpacyDialogComponent, {
-            data: {
-              comment,
-              commentLang,
-              commentBodyChecked: result.text
-            }
-          });
-          dialogRef.afterClosed().subscribe(dialogResult => {
-            if (dialogResult) {
-              this.dialogRef.close(dialogResult);
-            }
-          });
         } else {
           comment.language = CommentLanguage.auto;
           this.dialogRef.close(comment);
@@ -91,4 +86,44 @@ export class CreateCommentComponent implements OnInit {
         this.isSendingToSpacy = false;
       });
   }
+
+  private callDeepL(comment: Comment, text: string, result: LanguagetoolResult) {
+    let target = TargetLang.EN_US;
+    const code = result.language.detectedLanguage.code.toUpperCase().split('-')[0];
+    if (code.startsWith(SourceLang.EN)) {
+      target = TargetLang.DE;
+    }
+    DeepLDialogComponent.generateDeeplDelta(this.deeplService, comment.body, target)
+      .subscribe(([improvedBody, improvedText]) => {
+        comment.body = improvedBody;
+        this.callSpacy(comment, improvedText, result, true);
+      }, () => {
+        this.callSpacy(comment, text, result, true);
+      });
+  }
+
+  private callSpacy(comment: Comment, text: string, result: LanguagetoolResult, forward = false) {
+    const commentLang = this.languagetoolService.mapLanguageToSpacyModel(result.language.code as Language);
+    const selectedLangExtend = this.commentComponent.selectedLang[2] === '-' ?
+      this.commentComponent.selectedLang.substr(0, 2) : this.commentComponent.selectedLang;
+    // Store language if it was auto-detected
+    if (this.commentComponent.selectedLang === 'auto') {
+      comment.language = Comment.mapModelToLanguage(commentLang);
+    } else if (CommentLanguage[selectedLangExtend]) {
+      comment.language = CommentLanguage[selectedLangExtend];
+    }
+    const dialogRef = this.dialog.open(SpacyDialogComponent, {
+      data: {
+        comment,
+        commentLang,
+        commentBodyChecked: text,
+        forward
+      }
+    });
+    dialogRef.afterClosed().subscribe(dialogResult => {
+      if (dialogResult) {
+        this.dialogRef.close(dialogResult);
+      }
+    });
+  }
 }
diff --git a/src/app/components/shared/_dialogs/deep-ldialog/deep-ldialog.component.ts b/src/app/components/shared/_dialogs/deep-ldialog/deep-ldialog.component.ts
index ac5e45af6..5844ca5d9 100644
--- a/src/app/components/shared/_dialogs/deep-ldialog/deep-ldialog.component.ts
+++ b/src/app/components/shared/_dialogs/deep-ldialog/deep-ldialog.component.ts
@@ -10,7 +10,7 @@ import { Observable } from 'rxjs';
 import { map } from 'rxjs/operators';
 import { CreateCommentKeywords } from '../../../../utils/create-comment-keywords';
 
-interface ResultValue {
+export interface ResultValue {
   body: string;
   text: string;
   view: ViewCommentDataComponent;
@@ -95,7 +95,7 @@ export class DeepLDialogComponent implements OnInit, AfterViewInit {
       text: this.data.improvedText,
       view: this.improved
     };
-    this.radioButtonValue = this.improvedValue;
+    this.radioButtonValue = this.normalValue;
   }
 
   ngAfterViewInit() {
@@ -124,7 +124,7 @@ export class DeepLDialogComponent implements OnInit, AfterViewInit {
       }
       if (ViewCommentDataComponent.checkInputData(current.body, current.text,
         this.translateService, this.notificationService, this.data.maxTextCharacters, this.data.maxDataCharacters)) {
-        this.data.onClose(current.body, current.text, current.view);
+        this.data.onClose(current);
         this.dialogRef.close(true);
       }
     };
diff --git a/src/app/components/shared/_dialogs/spacy-dialog/spacy-dialog.component.ts b/src/app/components/shared/_dialogs/spacy-dialog/spacy-dialog.component.ts
index b59c7c531..d31762cc2 100644
--- a/src/app/components/shared/_dialogs/spacy-dialog/spacy-dialog.component.ts
+++ b/src/app/components/shared/_dialogs/spacy-dialog/spacy-dialog.component.ts
@@ -53,6 +53,10 @@ export class SpacyDialogComponent implements OnInit, AfterContentInit {
   ngAfterContentInit(): void {
     if (this.langSupported) {
       this.evalInput(this.commentLang);
+    } else if (this.data.forward) {
+      this.keywords = [];
+      this.keywordsOriginal = [];
+      setTimeout(() => this.buildCreateCommentActionCallback()());
     }
   }
 
@@ -76,6 +80,11 @@ export class SpacyDialogComponent implements OnInit, AfterContentInit {
 
   evalInput(model: Model) {
     this.isLoading = true;
+    const afterFinish = () => {
+      if (this.data.forward) {
+        this.buildCreateCommentActionCallback()();
+      }
+    };
 
     // N at first pos = all Nouns(NN de/en) including singular(NN, NNP en), plural (NNPS, NNS en), proper Noun(NNE, NE de)
     this.spacyService.getKeywords(this.commentBodyChecked, model)
@@ -95,8 +104,10 @@ export class SpacyDialogComponent implements OnInit, AfterContentInit {
         this.keywordsOriginal = [];
         this.hasKeywordsFromSpacy = false;
         this.isLoading = false;
+        afterFinish();
       }, () => {
         this.isLoading = false;
+        afterFinish();
       });
   }
 
diff --git a/src/app/components/shared/write-comment/write-comment.component.html b/src/app/components/shared/write-comment/write-comment.component.html
index 9989ec458..af8aca65b 100644
--- a/src/app/components/shared/write-comment/write-comment.component.html
+++ b/src/app/components/shared/write-comment/write-comment.component.html
@@ -88,7 +88,7 @@
       [showDivider]="false"
       [spacing]="false"
       [cancelButtonClickAction]="buildCloseDialogActionCallback()"
-      [confirmButtonClickAction]="buildCreateCommentActionCallback()"
+      [confirmButtonClickAction]="buildCreateCommentActionCallback(this.onSubmit)"
     ></app-dialog-action-buttons>
   </ars-col>
 </ars-row>
diff --git a/src/app/components/shared/write-comment/write-comment.component.ts b/src/app/components/shared/write-comment/write-comment.component.ts
index 994fbffc0..5e0e5152c 100644
--- a/src/app/components/shared/write-comment/write-comment.component.ts
+++ b/src/app/components/shared/write-comment/write-comment.component.ts
@@ -6,10 +6,13 @@ import { NotificationService } from '../../../services/util/notification.service
 import { LanguageService } from '../../../services/util/language.service';
 import { ViewCommentDataComponent } from '../view-comment-data/view-comment-data.component';
 import { DeepLService, SourceLang, TargetLang } from '../../../services/http/deep-l.service';
-import { DeepLDialogComponent } from '../_dialogs/deep-ldialog/deep-ldialog.component';
+import { DeepLDialogComponent, ResultValue } from '../_dialogs/deep-ldialog/deep-ldialog.component';
 import { MatDialog } from '@angular/material/dialog';
 import { FormControl, Validators } from '@angular/forms';
 
+type SubmitFunction = (commentData: string, commentText: string, selectedTag: string, name?: string,
+                       verifiedWithoutDeepl?: boolean) => any;
+
 @Component({
   selector: 'app-write-comment',
   templateUrl: './write-comment.component.html',
@@ -22,7 +25,8 @@ export class WriteCommentComponent implements OnInit {
   @Input() isModerator = false;
   @Input() tags: string[];
   @Input() onClose: () => any;
-  @Input() onSubmit: (commentData: string, commentText: string, selectedTag: string, name?: string) => any;
+  @Input() onSubmit: SubmitFunction;
+  @Input() onDeeplSubmit: SubmitFunction;
   @Input() isSpinning = false;
   @Input() disableCancelButton = false;
   @Input() confirmLabel = 'save';
@@ -46,6 +50,7 @@ export class WriteCommentComponent implements OnInit {
   questionerNameFormControl = new FormControl('', [
     Validators.minLength(2), Validators.maxLength(20)
   ]);
+  private _wasVerifiedWithoutDeepl = false;
 
   constructor(private notification: NotificationService,
               private languageService: LanguageService,
@@ -75,8 +80,8 @@ export class WriteCommentComponent implements OnInit {
     return () => this.onClose();
   }
 
-  buildCreateCommentActionCallback(): () => void {
-    if (!this.onSubmit) {
+  buildCreateCommentActionCallback(func: SubmitFunction): () => void {
+    if (!func) {
       return undefined;
     }
     return () => {
@@ -88,7 +93,8 @@ export class WriteCommentComponent implements OnInit {
       }
       if (ViewCommentDataComponent.checkInputData(this.commentData.currentData, this.commentData.currentText,
         this.translateService, this.notification, this.maxTextCharacters, this.maxDataCharacters) && allowed) {
-        this.onSubmit(this.commentData.currentData, this.commentData.currentText, this.selectedTag, this.questionerNameFormControl.value);
+        func(this.commentData.currentData, this.commentData.currentText, this.selectedTag,
+          this.questionerNameFormControl.value, this._wasVerifiedWithoutDeepl);
       }
     };
   }
@@ -121,12 +127,13 @@ export class WriteCommentComponent implements OnInit {
       }
       const previous = this.commentData.currentData;
       this.openDeeplDialog(previous, rawText, wordsCheck,
-        (data: string, text: string, view: ViewCommentDataComponent) => {
-          if (view === this.commentData) {
+        (selected) => {
+          if (selected.view === this.commentData) {
+            this._wasVerifiedWithoutDeepl = true;
             this.commentData.buildMarks(rawText, wordsCheck);
           } else {
-            this.commentData.currentData = data;
-            this.commentData.copyMarks(view);
+            this.commentData.currentData = selected.body;
+            this.commentData.copyMarks(selected.view);
           }
         });
     }, () => {
@@ -145,7 +152,7 @@ export class WriteCommentComponent implements OnInit {
   private openDeeplDialog(body: string,
                           text: string,
                           result: LanguagetoolResult,
-                          onClose: (data: string, text: string, view: ViewCommentDataComponent) => void) {
+                          onClose: (selected: ResultValue) => void) {
     let target = TargetLang.EN_US;
     const code = result.language.detectedLanguage.code.toUpperCase().split('-')[0];
     const source = code in SourceLang ? SourceLang[code] : null;
@@ -156,10 +163,10 @@ export class WriteCommentComponent implements OnInit {
       .subscribe(([improvedBody, improvedText]) => {
         this.isSpellchecking = false;
         if (improvedText.replace(/\s+/g, '') === text.replace(/\s+/g, '')) {
-          onClose(body, text, this.commentData);
+          onClose({ body, text, view: this.commentData });
           return;
         }
-        this.dialog.open(DeepLDialogComponent, {
+        const instance = this.dialog.open(DeepLDialogComponent, {
           width: '900px',
           maxWidth: '100%',
           data: {
@@ -175,14 +182,17 @@ export class WriteCommentComponent implements OnInit {
             target: DeepLService.transformSourceToTarget(source),
             usedTarget: target
           }
-        }).afterClosed().subscribe((val) => {
+        });
+        instance.afterClosed().subscribe((val) => {
           if (val) {
-            this.buildCreateCommentActionCallback()();
+            this.buildCreateCommentActionCallback(this.onDeeplSubmit)();
+          } else {
+            onClose({ body, text, view: this.commentData });
           }
         });
       }, (_) => {
         this.isSpellchecking = false;
-        onClose(body, text, this.commentData);
+        onClose({ body, text, view: this.commentData });
       });
   }
 
-- 
GitLab