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 { DirectAdminApiService } from '@fleio-api/plugins/directadmin/directadmin-api.service';
import { IDirectAdminOSModel } from '@fleio-api/plugins/directadmin/model/direct-admin-os.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-change-os-dialog',
  templateUrl: './change-os-dialog.component.html',
  styleUrls: ['./change-os-dialog.component.scss']
})
export class ChangeOSDialogComponent implements IBaseDialog, OnInit {
  changeOSForm = this.formBuilder.group({
    os: ['', Validators.required],
  });
  dialogTitle = $localize`Change DirectAdmin license Operating System`;
  dialogActions: Array<IAction> = [
    new DialogCallbackAction({
      name: $localize`Change Operating System`,
      primary: true,
      callback: () => this.changeOS(),
    }),
  ];
  dialogForm = this.changeOSForm;
  loading = false;
  public serviceResources: IDirectAdminServiceResources;
  osList: IDirectAdminOSModel[];

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

  ngOnInit() {
    this.loading = true;
    this.directAdminApi.getOSList().subscribe(osList => {
      this.osList = osList;
      this.loading = false;
    });
    this.serviceResources = this.data.service_resources;
    this.changeOSForm.patchValue(this.serviceResources);
  }

  changeOS() {
    if (!this.changeOSForm.valid) {
      return;
    }

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