import { HttpErrorResponse, HttpEvent, HttpHandler, HttpInterceptor, HttpRequest, HttpResponse } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { UiModalService } from '../modal.service';
import { UiDialogModalComponent } from './dialog-modal.component';
import { Observable, throwError } from 'rxjs';
import { catchError, tap } from 'rxjs/operators';
import { DialogModel } from './dialog.model';
import { ToastService } from '@core/toast';

@Injectable()
export class OpenDialogInterceptor implements HttpInterceptor {
  constructor(private _modal: UiModalService, private _toast: ToastService) {}

  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    return next.handle(req).pipe(
      tap((response) => {
        if (response instanceof HttpResponse) {
          if (response?.body?.dialog?.area === 'dialog') {
            this.openDialog(response.body.dialog);
          }
          if (response?.body?.dialog?.area === 'Toaster') {
            this.createToast(response.body.dialog);
          }
        }
      }),
      catchError((error: HttpErrorResponse) => {
        if (error?.error?.dialog?.area === 'dialog') {
          this.openDialog(error.error.dialog);
        }
        if (error?.error?.dialog?.area === 'Toaster') {
          this.createToast(error.error.dialog);
        }
        return throwError(error);
      })
    );
  }

  createToast(dialog: DialogModel) {
    this._toast.create({
      title: dialog.title,
      text: dialog.content,
    });
  }

  openDialog(model: DialogModel) {
    this._modal.open({
      content: UiDialogModalComponent,
      data: model,
      title: model.title,
      config: {
        canClose: (model.settings & 1) === 1,
        hasBackdrop: (model.settings & 2) === 2,
      },
    });
  }
}
