import { Component, OnInit } from '@angular/core';
import { DetailsFormBase } from '@objects-view/details-form-base';
import { UntypedFormBuilder, Validators } from '@angular/forms';
import { Router } from '@angular/router';
import { ConfigService } from '@shared/config/config.service';
import { NotificationService } from '@shared/ui-api/notification.service';
import { ITermsOfServiceModel } from '@fleio-api/core/model/terms-of-service.model';
import { SettingsApiService } from '@fleio-api/core/settings-api.service';
import { catchError } from 'rxjs/operators';
import { EMPTY, Observable } from 'rxjs';
import { ThemingService } from '@shared/ui/theming/theming.service';

@Component({
  selector: 'app-edit-terms-of-service-form',
  templateUrl: './edit-terms-of-service-form.component.html',
  styleUrls: ['./edit-terms-of-service-form.component.scss']
})
export class EditTermsOfServiceFormComponent extends DetailsFormBase<ITermsOfServiceModel> implements OnInit {
  termsOfServiceForm = this.formBuilder.group({
    title: ['', Validators.required],
    version: ['', Validators.required],
    draft: [false],
    content: ['', Validators.required],
  });
  tinyMCEOptions = null;
  isNew = false;
  tosSaveSubmitted = false;
  fieldRequiredTxt = $localize`This field is required!`;
  addTxt = $localize`Add new terms of service`;
  saveTxt = $localize`Save terms of service`;

  constructor(
    private formBuilder: UntypedFormBuilder,
    private router: Router,
    public config: ConfigService,
    private notificationService: NotificationService,
    private settingsAPI: SettingsApiService,
    private themingService: ThemingService,
  ) {
    super();
  }

  ngOnInit() {
    if (this.object && this.object.id) {
      this.termsOfServiceForm.patchValue(this.object);
    } else {
      this.isNew = true;
    }

    if (this.config && this.config.current) {
      this.tinyMCEOptions = this.themingService.getTinyMceOptions();
    }
  }

  handleTinyKeyDown(event: any) {
    if (event && event.event && event.event.ctrlKey && event.event.keyCode === 13) {
      event.event.preventDefault();
      this.saveTermsOfService();
    }
  }

  saveTermsOfService() {
    this.tosSaveSubmitted = true;
    if (this.termsOfServiceForm.invalid) {
      this.displayControlErrors();
      return;
    }

    const termsOfService = this.termsOfServiceForm.value as ITermsOfServiceModel;
    let request: Observable<any>;
    if (this.isNew) {
      request = this.settingsAPI.createTermsOfService(termsOfService);
    } else {
      termsOfService.id = this.object.id;
      request = this.settingsAPI.saveTermsOfService(termsOfService);
    }

    this.objectController.loading = true;
    request.pipe(catchError((error) => {
      this.objectController.loading = false;
      if (error.error) {
        this.setErrors(error.error);
        return EMPTY;
      } else {
        throw error;
      }
    })).subscribe(() => {
      this.notificationService.showMessage(
        this.isNew ? $localize`Terms of service created` : $localize`Terms of service saved`,
      );
      this.router.navigateByUrl(
        this.config.getPanelUrl('settings/general#terms-of-service'),
      ).then(() => {
      });
    });
  }
}
