import { Component, Inject, OnInit } from '@angular/core';
import { UntypedFormBuilder, Validators } from '@angular/forms';
import { MAT_DIALOG_DATA, MatDialogRef } from '@angular/material/dialog';
import { ServicesApiService } from '@fleio-api/billing/services/service-api.service';
import { NotificationService } from '@shared/ui-api/notification.service';
import { IServiceResources } from '@fleio-api/billing/model/service.model';
import { IServiceResources as IDirectAdminServiceResources } from '@shared/plugins/interfaces/directadmin/service-resources';
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-change-ip-dialog',
  templateUrl: './change-ip-dialog.component.html',
  styleUrls: ['./change-ip-dialog.component.scss']
})
export class ChangeIPDialogComponent implements IBaseDialog, OnInit {
  changeIPForm = this.formBuilder.group({
    ip_address: ['', Validators.required],
  });
  dialogTitle = $localize`Change DirectAdmin license IP`;
  dialogActions: Array<IAction> = [
    new DialogCallbackAction({
      name: $localize`Change IP`,
      primary: true,
      callback: () => this.changeIP(),
    }),
  ];
  dialogForm = this.changeIPForm;
  loading = false;
  public serviceResources: IDirectAdminServiceResources;

  constructor(
    public dialogRef: MatDialogRef<ChangeIPDialogComponent>,
    @Inject(MAT_DIALOG_DATA) public data: IServiceResources,
    private servicesApi: ServicesApiService,
    private notificationService: NotificationService,
    private formBuilder: UntypedFormBuilder,
  ) {
  }

  ngOnInit() {
    this.serviceResources = this.data.service_resources;
    this.changeIPForm.patchValue(this.serviceResources);
  }

  changeIP() {
    if (!this.changeIPForm.valid) {
      return;
    }

    this.loading = true;
    this.servicesApi.pluginAction(
      this.data.service_id, 'change_ip', {
        ip_address: this.changeIPForm.value.ip_address
      }
    ).subscribe({
      next: () => {
        this.dialogRef.close('saved');
      }, error: () => {
        this.notificationService.showMessage($localize`Failed to save new IP, please check logs for details.`);
      }
    }).add(() => {
      this.loading = false;
    });
  }
}
