import { Component, Inject, OnInit } from '@angular/core';
import { UntypedFormBuilder, Validators } from '@angular/forms';
import { MAT_DIALOG_DATA, MatDialogRef } from '@angular/material/dialog';
import { IClientModel } from '@fleio-api/client-user/model/client.model';
import { ClientsApiService } from '@fleio-api/client-user/client/clients-api.service';
import { NotificationService } from '@shared/ui-api/notification.service';
import { catchError } from 'rxjs/operators';
import { EMPTY } from 'rxjs';
import { IConfigurationModel } from '@fleio-api/configurations/model/configuration.model';
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-configuration-dialog',
  templateUrl: './change-configuration-dialog.component.html',
  styleUrls: ['./change-configuration-dialog.component.scss']
})
export class ChangeConfigurationDialogComponent implements IBaseDialog, OnInit {
  changeConfigurationFrom = this.formBuilder.group({
    selectedConfiguration: [null, Validators.required]
  });
  dialogTitle = $localize`Change client ${this.data?.client?.name} configuration`;
  dialogActions: Array<IAction> = [
    new DialogCallbackAction({
      name: $localize`Change configuration`,
      primary: true,
      callback: () => this.changeConfiguration(),
    }),
  ];
  dialogForm = this.changeConfigurationFrom;
  loading = false;

  selectedConfiguration = this.changeConfigurationFrom.controls.selectedConfiguration;
  availableConfigurations: IConfigurationModel[];

  constructor(
    public dialogRef: MatDialogRef<ChangeConfigurationDialogComponent>,
    @Inject(MAT_DIALOG_DATA) public data: {
      client: IClientModel;
      configuration: IConfigurationModel;
    },
    private formBuilder: UntypedFormBuilder,
    private clientsApi: ClientsApiService,
    private notificationService: NotificationService,
  ) {
  }

  ngOnInit() {
    if (this.data && this.data.client) {
      this.loading = true;
      this.clientsApi.getConfigurationForClient(this.data.client.id).subscribe(availableConfigurations => {
        this.availableConfigurations = availableConfigurations.configurations;
        this.loading = false;
      });
    }
  }

  changeConfiguration() {
    this.loading = true;
    this.clientsApi.changeConfiguration(this.data.client.id, this.selectedConfiguration.value).pipe(
      catchError(() => {
        this.notificationService.showMessage($localize`Failed to change configuration`);
        return EMPTY;
      }),
    ).subscribe(() => {
      this.dialogRef.close(true);
    }).add(() => {
      this.loading = false;
    });
  }
}
