import { Component, OnInit } from '@angular/core';
import { DetailsComponentBase } from '@objects-view/details-component-base';
import { IBaseFleioObjectModel } from '@fleio-api/base-model/base-fleio-object.model';
import { UntypedFormBuilder } from '@angular/forms';
import { NotificationService } from '@shared/ui-api/notification.service';
import { IOpenStackAdvancedSettingsModel } from '@fleio-api/openstack/model/openstack-advanced-settings.model';
import { SettingsOpenstackApiService } from '@fleio-api/core/settings-openstack-api.service';

@Component({
  selector: 'app-openstack-advanced-settings',
  templateUrl: './openstack-advanced-settings.component.html',
  styleUrls: ['./openstack-advanced-settings.component.scss']
})
export class OpenstackAdvancedSettingsComponent extends DetailsComponentBase<IBaseFleioObjectModel> implements OnInit {
  loadingSettings = false;
  osAdvancedSettingsForm = this.formBuilder.group({
    end_ghost_usage_on_sync: [false],
  });
  private osAdvancedSettings: IOpenStackAdvancedSettingsModel;

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

  ngOnInit(refreshTimerInterval?: number) {
    super.ngOnInit(refreshTimerInterval);
  }

  protected initTabData() {
    this.loadingSettings = true;
    this.settingsOpenstackApi.getAdvancedSettings().subscribe({
      next: advancedSettings => {
        this.osAdvancedSettings = advancedSettings;
        this.osAdvancedSettingsForm.patchValue(advancedSettings);
      }, error: error => {
        if (error.status === 403) {
          this.osAdvancedSettingsForm.disable();
        }
      }
    }).add(() => {
      this.loadingSettings = false;
    });
  }

  saveSettings() {
    const advancedSettings = this.osAdvancedSettingsForm.getRawValue();
    this.objectController.loading = true;
    this.settingsOpenstackApi.saveAdvancedSettings(advancedSettings).subscribe({
      next: () => {
        this.notificationService.showMessage($localize`OpenStack advanced settings saved`);
      }, error: () => {
        this.notificationService.showMessage($localize`Failed to save OpenStack advanced settings, check logs for details`);
      }
    }).add(() => {
      this.objectController.loading = false;
    });
  }
}
