import { Component, OnInit, ViewChild } from '@angular/core';
import { DetailsComponentBase } from '@objects-view/details-component-base';
import { IDbaasInstanceModel } from '@fleio-api/openstack/model/dbaas-instance.model';
import { ConfigService } from '@shared/config/config.service';
import { DbaasInstancesApiService } from '@fleio-api/openstack/dbaas/dbaas-instances-api.service';
import { NotificationService } from '@shared/ui-api/notification.service';
import { UntypedFormBuilder } from '@angular/forms';

@Component({
  selector: 'app-dbaas-instance-root-user-tab',
  templateUrl: './dbaas-instance-root-user-tab.component.html',
  styleUrls: ['./dbaas-instance-root-user-tab.component.scss']
})
export class DbaasInstanceRootUserTabComponent extends DetailsComponentBase<IDbaasInstanceModel> implements OnInit {
  @ViewChild('formErrors') formErrors;
  enableRootForm = this.formBuilder.group({
    root_password: [''],
  });
  rootEnabled: boolean;
  enablingRoot = false;
  disablingRoot = false;
  loadingHistory = false;
  rootPassword: string;
  loading = false;
  previewPassword = false;
  rootEnabledHistory: {
    id: string;
    user: string;
    enabled: Date;
  };

  constructor(
    public config: ConfigService,
    private notificationService: NotificationService,
    private dbaasInstancesApiService: DbaasInstancesApiService,
    private formBuilder: UntypedFormBuilder,
  ) {
    super();
  }

  protected tabActivated() {
    super.tabActivated();
    this.loading = true;
    this.dbaasInstancesApiService.getRootEnabledStatus(this.object.id).subscribe({
      next: value => {
        this.rootEnabled = value.is_instance_root_enabled;
        this.loading = false;
      }, error: error => {
        this.notificationService.showMessage(error.error.detail);
      }
    });
  }

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

  loadRootEnabled(event) {
    event.preventDefault();
    this.loadingHistory = true;
    this.dbaasInstancesApiService.getRootEnabledHistory(this.object.id).subscribe(response => {
      this.rootEnabledHistory = response;
    }).add(() => {
      this.loadingHistory = false;
    });
  }

  enableRoot(event) {
    event.preventDefault();
    this.enablingRoot = true;
    const formValue = this.enableRootForm.value;
    this.dbaasInstancesApiService.enableRoot(this.object.id, formValue.root_password).subscribe({
      next: (value) => {
        if (formValue.root_password) {
          // don't show password if it wasn't generated by OpenStack
          this.rootPassword = null;
        } else {
          this.rootPassword = value.root_password;
        }
        this.rootEnabled = true;
        this.notificationService.showMessage($localize`Root enabled.`);
      }, error: (error) => {
        if (error.error?.root_password) {
          this.enableRootForm.controls.root_password.setErrors({
            backend: true,
            fleio_error: error.error.root_password,
          });
          this.enableRootForm.controls.root_password.markAsTouched();
        } else {
          this.formErrors.setBackendErrors(error.error);
        }
      }
    }).add(() => {
      this.enablingRoot = false;
    });
  }

  disableRoot(event) {
    event.preventDefault();
    this.disablingRoot = true;
    this.dbaasInstancesApiService.disableRoot(this.object.id).subscribe({
      next: value => {
        this.notificationService.showMessage(value.detail);
        this.rootEnabled = false;
      }, error: error => {
        if (error?.error?.detail) {
          this.notificationService.showMessage(error.error.detail);
        } else {
          this.notificationService.showMessage($localize`Failed to disable root.`);
        }
      }
    }).add(() => {
      this.disablingRoot = false;
    });
  }
}
