import {
  Component,
  ElementRef,
  EventEmitter,
  Input,
  OnChanges,
  OnInit,
  Output,
  SimpleChanges,
  ViewChild
} from "@angular/core";
import {ResultLandingInfo} from "../../utils/entities/resultLandingInfo";
import {EnvProperties} from "../../utils/properties/env-properties";
import {UntypedFormArray, UntypedFormBuilder, UntypedFormGroup, Validators} from "@angular/forms";
import {AlertModal} from "../../utils/modal/alert";
import {HelperFunctions} from "../../utils/HelperFunctions.class";
import {OrganizationInfo} from "../../utils/entities/organizationInfo";
import {ProjectInfo} from "../../utils/entities/projectInfo";
import {DataProviderInfo} from "../../utils/entities/dataProviderInfo";
import {EmailService} from "../../utils/email/email.service";
import {Composer} from "../../utils/email/composer";
import {Subscriber} from "rxjs";

@Component({
  selector: 'feedback',
  templateUrl: 'feedback.component.html'
})
export class FeedbackComponent implements OnInit, OnChanges {
  @ViewChild('feedback') feedback: ElementRef;
  @ViewChild('backModal') backModal: AlertModal;
  @Input() showForm: boolean = false;
  @Output() showFormChange: EventEmitter<boolean> = new EventEmitter<boolean>();
  @Input() resultLandingInfo: ResultLandingInfo = null;
  @Input() organizationInfo: OrganizationInfo = null;
  @Input() projectInfo: ProjectInfo = null;
  @Input() dataProviderInfo: DataProviderInfo = null;
  @Input() title: string = null;
  @Input() properties: EnvProperties = null;
  @Input() entityType: string = null;
  @Input() fields: string[] = [];
  @Input() preSelectedField: string = "";
  
  public sending: boolean = false;
  public sent: boolean = false;
  public error: boolean = false;
  public form: UntypedFormGroup;
  public url: string = null;
  public recipients: string[] = [];
  subscriptions = [];
  
  constructor(private fb: UntypedFormBuilder,
              private emailService: EmailService) {
  }
  
  ngOnDestroy() {
    this.subscriptions.forEach(subscription => {
      if (subscription instanceof Subscriber) {
        subscription.unsubscribe();
      }
    });
  }
  
  ngOnInit(): void {
    if (typeof window !== "undefined") {
      this.url = window.location.href;
    }
    if (this.resultLandingInfo) {
      this.title = this.resultLandingInfo.title;
    } else if (this.organizationInfo) {
      this.title = this.organizationInfo.title.name;
    } else if (this.dataProviderInfo) {
      this.title = this.dataProviderInfo.title.name;
    }
    this.recipients = [this.properties.feedbackmail];
    this.init();
  }
  
  ngOnChanges(changes: SimpleChanges): void {
    if (changes.showForm) {
      this.init();
    }
  }
  
  init() {
    this.sent = false;
    this.form = this.fb.group({
      name: this.fb.control(this.title),
      url: this.fb.control(this.url),
      email: this.fb.control('', Validators.email),
      issues: this.fb.array([], Validators.required),
      recaptcha: this.fb.control('', Validators.required),
    });
    this.addIssue();
  }
  
  public addIssue() {
    let issue: UntypedFormGroup = this.fb.group({
      field: this.fb.control(this.preSelectedField, Validators.required),
      report: this.fb.control('', Validators.required)
    });
    this.issues.push(issue);
  }
  
  public removeIssue(index: number) {
    this.issues.removeAt(index);
  }
  
  public get issues(): UntypedFormArray {
    return <UntypedFormArray>this.form.get('issues');
  }
  
  changeShowForm(value: boolean) {
    this.showFormChange.emit(value);
    HelperFunctions.scroll();
  }
  
  public openBackModal() {
    this.backModal.alertTitle = 'Go back to ' + this.entityType + '\'s page';
    this.backModal.message = 'All changes will be deleted. Are you sure you want to proceed?';
    this.backModal.okButtonText = 'Yes';
    this.backModal.cancelButtonText = 'No';
    this.backModal.open();
  }
  
  public handleRecaptcha(captchaResponse: string) {
    this.form.get('recaptcha').setValue(captchaResponse);
  }
  
  public sendReport() {
    this.sending = true;
    this.subscriptions.push(this.emailService.contact(this.properties,
      Composer.composeEmailForFeedback(this.form.value, this.recipients), this.form.get('recaptcha').value).subscribe(sent => {
      this.error = !sent;
      if (sent) {
        if (this.form.get('email').value !== '') {
          this.subscriptions.push(this.emailService.contact(this.properties,
            Composer.composeEmailForUserAfterFeedback([this.form.get('email').value])).subscribe(sent => {
            if (sent) {
              //console.log('An email has been sent to user ' + this.form.get('email').value);
            }
          }));
        }
        this.init();
        this.sent = true;
      }
      this.sending = false;
    }, error => {
      console.log(error);
      this.error = true;
      this.sending = false;
    }));
  }
}
