import { ChangeDetectorRef, Component, NgZone } from '@angular/core';
import { DetailsComponentBase } from '@objects-view/details-component-base';
import { ISecurityGroupModel } from '@fleio-api/openstack/model/security-group.model';
import { ConfigService } from '@shared/config/config.service';
import { FleioId } from '@fleio-api/base-model/base-fleio-object.model';
import { of } from 'rxjs';
import { NotificationService } from '@shared/ui-api/notification.service';
import { SecurityGroupsApiService } from '@fleio-api/openstack/security-groups/security-groups-api.service';
import { catchError, map } from 'rxjs/operators';

@Component({
  selector: 'app-security-groups-details-overview',
  templateUrl: './security-groups-details-overview.component.html',
  styleUrls: ['./security-groups-details-overview.component.scss']
})
export class SecurityGroupsDetailsOverviewComponent extends DetailsComponentBase<ISecurityGroupModel> {
  displayedColumns = ['direction', 'type', 'protocol', 'ports', 'cidr', 'remote_group', 'description', 'actions'];
  deleteRuleTooltip = $localize`Delete rule`;

  constructor(
    public config: ConfigService,
    private notificationService: NotificationService,
    private securityGroupsApiService: SecurityGroupsApiService,
    ngZone: NgZone,
    changeDetectorRef: ChangeDetectorRef,
  ) {
    super(ngZone, changeDetectorRef, config);
  }

  protected refreshData() {
    this.securityGroupsApiService.get(this.object.id).subscribe(result => {
      this.objectController.object = result;
    });
  }

  deleteRule(ruleId: FleioId) {
    this.notificationService.confirmDialog({
      title: $localize`Delete security group rule ${ruleId}?`,
      message: $localize`Are you sure?`,
      yesAction: () => {
        return this.securityGroupsApiService.deleteRule(this.object.id, ruleId).pipe(map(() => {
            this.refreshData();
            this.notificationService.showMessage('Rule deleted');
            return null;
          }), catchError(() => {
            return of({success: false, message: 'Failed to delete rule, please contact support'});
          })
        );
      }
    }).subscribe(() => {
    });
  }

}
