import { Component, OnDestroy, OnInit } from '@angular/core';
import { IBaseFleioObjectModel } from '@fleio-api/base-model/base-fleio-object.model';
import { DetailsFormBase } from '@objects-view/details-form-base';
import { UntypedFormBuilder, Validators } from '@angular/forms';
import { SettingsApiService } from '@fleio-api/core/settings-api.service';
import { ISignupSettingsModel } from '@fleio-api/core/model/signup-settings.model';
import { IMessageTemplateModel } from '@fleio-api/core/model/message-template.model';
import { EMPTY } from 'rxjs';
import { catchError } from 'rxjs/operators';
import { NotificationService } from '@shared/ui-api/notification.service';

@Component({
  selector: 'app-sign-up',
  templateUrl: './sign-up-form.component.html',
  styleUrls: ['./sign-up-form.component.scss']
})
export class SignUpFormComponent
  extends DetailsFormBase<IBaseFleioObjectModel> implements OnInit, OnDestroy {

  loadingSettings: boolean;
  updatingControls: boolean;
  signupSettings: ISignupSettingsModel;
  messageTemplates: IMessageTemplateModel[];

  signupSettingsForm = this.formBuilder.group({
    require_captcha: [false],
    require_confirmation: [false],
    confirm_email_address_on_change: [true],
    consider_existing_users_have_email_verified: [true],
    email_confirmation_template: ['', Validators.required],
    allow_free_email_addresses: [true],
    forbidden_domains_for_email_signup: [''],
    domains_for_email_signup_whitelist: [''],
  });

  showConfirmEmailOpts = false;

  constructor(
    private formBuilder: UntypedFormBuilder, private settingsApi: SettingsApiService,
    private notificationService: NotificationService,
  ) {
    super();
  }

  protected initTabData() {
    this.loadingSettings = true;
    this.settingsApi.getSignupSettings().subscribe(signupInfo => {
        this.signupSettings = signupInfo.signup_settings;
        this.messageTemplates = signupInfo.message_templates;
        this.signupSettingsForm.patchValue(this.signupSettings);
      }, (error) => {
        if (error.status === 403) {
          this.signupSettingsForm.disable();
        }
      }
    ).add(() => {
      this.loadingSettings = false;
    });
  }


  ngOnInit(): void {
    super.ngOnInit();
    this.signupSettingsForm.valueChanges.subscribe(() => {
      if (!this.updatingControls) {
        this.updatingControls = true;
        this.updateControls();
        this.updatingControls = false;
      }
    });
  }

  private updateControls() {
    const require_confirmation = this.signupSettingsForm.controls.require_confirmation;
    if (require_confirmation.value) {
      if (!this.signupSettings.require_confirmation) {
        this.showConfirmEmailOpts = true;
      }
      this.signupSettingsForm.controls.email_confirmation_template.enable();
    } else {
      this.showConfirmEmailOpts = false;
      this.signupSettingsForm.controls.email_confirmation_template.disable();
    }
  }

  ngOnDestroy(): void {
  }

  saveSettings() {
    if (this.signupSettingsForm.invalid) {
      this.displayControlErrors();
      return EMPTY;
    }

    this.signupSettings = this.signupSettingsForm.value as ISignupSettingsModel;
    this.objectController.loading = true;
    this.settingsApi.saveSignupSettings(this.signupSettings).pipe(catchError((error) => {
      if (error.error) {
        this.setErrors(error.error);
        return EMPTY;
      } else {
        throw error;
      }
    })).subscribe(() => {
      this.notificationService.showMessage($localize`Signup settings saved`);
    }).add(() => {
      this.objectController.loading = false;
    });
  }
}
