import { Component, OnDestroy, OnInit } from '@angular/core';
import { DetailsFormBase } from '@objects-view/details-form-base';
import { IBaseFleioObjectModel } from '@fleio-api/base-model/base-fleio-object.model';
import { UntypedFormBuilder, Validators } from '@angular/forms';
import { SettingsOpenstackApiService } from '@fleio-api/core/settings-openstack-api.service';
import { IOpenstackDefaultsModel } from '@fleio-api/core/model/openstack-defaults.model';
import { EMPTY, Subscription } from 'rxjs';
import { catchError } from 'rxjs/operators';
import { NotificationService } from '@shared/ui-api/notification.service';
import { UiHelper } from '@shared/ui-api/helpers/ui-helper';
import { ValidatorsHelper } from '@shared/ui-api/helpers/validators-helper';

@Component({
  selector: 'app-defaults',
  templateUrl: './defaults.component.html',
  styleUrls: ['./defaults.component.scss']
})
export class DefaultsComponent extends DetailsFormBase<IBaseFleioObjectModel> implements OnInit, OnDestroy {
  protected focusFirstInput = false;
  defaultsLoading = false;
  defaultsForm = this.formBuilder.group({
    timeout: ['', ValidatorsHelper.requiredIntegerValidator],
    gnocchi_resource_types_timeout: ['', ValidatorsHelper.requiredIntegerValidator],
    default_roles: ['', Validators.required],
    default_roles_standard_user: ['', Validators.required],
    default_region: ['', Validators.required],
    project_domain_id: ['', Validators.required],
    default_project_name: ['', Validators.required],
    default_project_description: ['', Validators.required],
    force_config_drive_for_instance_creation: [false],
    use_instance_az_for_volume_on_instance_create: [true],
    hide_projects_and_api_users: [false],
    hide_project_ids: [''],
    use_api_username_template: [false],
    api_username_template: ['', Validators.required],
    hide_images_in_other_flavor_scope: [false],
    hide_unassigned_images: [false],
    default_lbaas_region: [''],
    retrieve_gnocchi_metadata: [true],
    default_gnocchi_region: [''],
    ptr_default_format: [''],
    ptr_default_format_ipv6: [''],
    inverse_address_zone_default_format: ['', Validators.email],
    ptr_records_force_lowercase: [false],
  });

  defaults: IOpenstackDefaultsModel;
  retrieveGnocchiMetadataSubscription: Subscription;

  apiUsernameTemplateHelpTxt = $localize`This text field appears if you check "Use API username template".
  It will override OpenStack API user usernames when end-users create them. Default template is
  "{{ user.email }}_{{ api_user_username }}". The {{ api_user_username }} placeholder which represents the actual
  username chosen by the end-user in the create form is mandatory to be used. Other string or number fields from the
  user or client record can also be used, e.g.: "{{ client.id }}", "{{ client.company }}", {{ user.id }}, etc.`;

  constructor(
    private formBuilder: UntypedFormBuilder, private settingsOpenstackApi: SettingsOpenstackApiService,
    private notificationService: NotificationService,
  ) {
    super();
  }

  ngOnInit(refreshTimerInterval?: number) {
    super.ngOnInit(refreshTimerInterval);
    this.defaultsForm.controls.use_api_username_template.valueChanges.subscribe(value => {
      if (value) {
        this.defaultsForm.controls.api_username_template.enable();
      } else {
        this.defaultsForm.controls.api_username_template.disable();
      }
    });
  }

  ngOnDestroy() {
    super.ngOnDestroy();
    if (this.retrieveGnocchiMetadataSubscription) {
      this.retrieveGnocchiMetadataSubscription.unsubscribe();
      this.retrieveGnocchiMetadataSubscription = null;
    }
  }

  initTabData() {
    this.defaultsLoading = true;
    if (!this.retrieveGnocchiMetadataSubscription) {
      this.retrieveGnocchiMetadataSubscription = this.defaultsForm.controls.retrieve_gnocchi_metadata.valueChanges.subscribe(
        value => {
          if (value) {
            this.defaultsForm.controls.default_gnocchi_region.enable();
          } else {
            this.defaultsForm.controls.default_gnocchi_region.disable();
          }
        });
    }
    this.settingsOpenstackApi.getDefaults().subscribe(defaults => {
      this.defaults = defaults;
      this.defaultsForm.patchValue(defaults);
    }).add(() => {
      this.defaultsLoading = false;
      UiHelper.focusAndSelectFirstInput(this.elementRef, this.changeDetector, true);
    });
  }

  save() {
    this.validate();
    if (this.formGroup.invalid) {
      this.displayControlErrors();
      return EMPTY;
    }

    const defaults = this.defaultsForm.getRawValue();
    if (!defaults.use_api_username_template) {
      delete defaults.api_username_template;
    }

    this.objectController.loading = true;
    return this.settingsOpenstackApi.saveDefaults(defaults).pipe(catchError((error) => {
      if (error.error) {
        this.setErrors(error.error);
        return EMPTY;
      } else {
        throw error;
      }
    })).subscribe((response) => {
      this.notificationService.showMessage(response.detail);
    }).add(() => {
      this.objectController.loading = false;
    });
  }
}
