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 { IAction } from '@objects-view/interfaces/actions/action';
import { DialogCallbackAction } from '@objects-view/actions/dialog-callback-action';
import { IBaseDialog } from '@shared/common-dialogs/base-dialog';

@Component({
  selector: 'app-change-name-dialog',
  templateUrl: './change-name-dialog.component.html',
  styleUrls: ['./change-name-dialog.component.scss']
})
export class ChangeNameDialogComponent implements IBaseDialog, OnInit {
  changeNameForm = this.formBuilder.group({
    name: ['', Validators.required],
  });
  dialogTitle = $localize`Change DirectAdmin license name`;
  dialogActions: Array<IAction> = [
    new DialogCallbackAction({
      name: $localize`Change name`,
      primary: true,
      callback: () => this.changeName(),
    }),
  ];
  dialogForm = this.changeNameForm;
  loading = false;
  public serviceResources: IDirectAdminServiceResources;

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

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

  changeName() {
    if (!this.changeNameForm.valid) {
      return;
    }

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