import { Component, Inject, OnInit, ViewChild } from '@angular/core';
import { UntypedFormBuilder, Validators } from '@angular/forms';
import { ISecurityGroupModel } from '@fleio-api/openstack/model/security-group.model';
import { NotificationService } from '@shared/ui-api/notification.service';
import { InstancesApiService } from '@fleio-api/openstack/instance/instances-api.service';
import { MAT_DIALOG_DATA, MatDialogRef } from '@angular/material/dialog';
import { IInstanceModel } from '@fleio-api/openstack/model/instance.model';
import { IBaseDialog } from '@shared/common-dialogs/base-dialog';
import { IAction } from '@objects-view/interfaces/actions/action';
import { DialogCallbackAction } from '@objects-view/actions/dialog-callback-action';

@Component({
  selector: 'app-instance-associate-security-group-dialog',
  templateUrl: './instance-associate-security-group-dialog.component.html',
  styleUrls: ['./instance-associate-security-group-dialog.component.scss']
})
export class InstanceAssociateSecurityGroupDialogComponent implements IBaseDialog, OnInit {
  @ViewChild('formErrors') formErrors;
  loading = false;
  backendErrors = {};
  associateSecurityGroupForm = this.formBuilder.group({
    group: ['', Validators.required]
  });
  dialogTitle = $localize`Associate security group to ${this.data?.instance?.name || this.data?.instance?.id}`;
  dialogActions: Array<IAction> = [
    new DialogCallbackAction({
      name: $localize`Associate group`,
      primary: true,
      callback: () => this.associateGroup(),
    }),
  ];
  dialogForm = this.associateSecurityGroupForm;
  securityGroups: Array<ISecurityGroupModel> = [];
  fieldRequiredTxt = $localize`This field is required!`;

  constructor(
    private formBuilder: UntypedFormBuilder,
    private notificationService: NotificationService,
    private instancesApi: InstancesApiService,
    public dialogRef: MatDialogRef<InstanceAssociateSecurityGroupDialogComponent>,
    @Inject(MAT_DIALOG_DATA) public data: {
      instance: IInstanceModel;
    },
  ) { }

  public associateGroup() {
    this.loading = true;
    if (!this.associateSecurityGroupForm.valid) {
      this.loading = false;
      return;
    }
    const value = this.associateSecurityGroupForm.value;
    this.instancesApi.associateSecurityGroup(this.data.instance.id, value.group).subscribe(response => {
      this.loading = false;
      this.dialogRef.close(true);
    }, error => {
      this.loading = false;
      this.formErrors.setBackendErrors(error.error.detail);
    });
  }

  ngOnInit(): void {
    if (this.data && this.data.instance) {
      this.loading = true;
      this.instancesApi.getAssociateSecurityGroupOptions(this.data.instance.id).subscribe(response => {
        this.securityGroups = response.groups;
        this.loading = false;
      }, error => {
        this.notificationService.showMessage($localize`Could not load associate security group options.`);
        this.dialogRef.close(false);
      });
    }
  }

}
