import { Component, Inject, OnInit } from '@angular/core';
import { MAT_DIALOG_DATA, MatDialogRef } from '@angular/material/dialog';
import { IObjectController } from '../interfaces/object-controller';
import { NotificationService } from '@shared/ui-api/notification.service';
import { RefreshService } from '@shared/ui-api/refresh.service';
import { ActionTypes } from '@objects-view/actions/action-types';
import { IDetailsTab } from '@objects-view/interfaces/details/details-tab';
import { IDetailsData } from '@objects-view/interfaces/details/details-data';
import { IAction } from '@objects-view/interfaces/actions/action';

@Component({
  selector: 'app-object-details-tab-dialog',
  templateUrl: './object-details-tab-dialog.component.html',
  styleUrls: ['./object-details-tab-dialog.component.scss']
})
export class ObjectDetailsTabDialogComponent implements OnInit {
  public actionTypes = ActionTypes;
  public tab: IDetailsTab;
  public detailsData: IDetailsData;
  executingAction = false;
  loaderTop = null;

  constructor(
    public dialogRef: MatDialogRef<ObjectDetailsTabDialogComponent>,
    @Inject(MAT_DIALOG_DATA) public data: {
      additionalClasses: string[];
      dialogTitle: string;
      objectController: IObjectController;
    },
    public notificationService: NotificationService,
    public refreshService: RefreshService,
  ) {
    if (!this.data.additionalClasses) {
      this.data.additionalClasses = [];
    }
    this.data.additionalClasses.push('on-dialog-card');
    if (this.data.objectController) {
      this.detailsData = this.data.objectController.getDetailsCardData();
      if (this.detailsData?.tabs?.length > 0) {
        this.tab = this.detailsData.tabs[0];
      }
    }
  }

  ngOnInit(): void {
  }

  onDialogScroll(event) {
    this.loaderTop = `${event.target.scrollTop}px`;
  }

  close() {
    this.dialogRef.close(false);
  }

  executeAction(action: IAction, $event: MouseEvent) {
    this.executingAction = true;
    action.execute(
      this.notificationService, this.refreshService, $event,
      (executedAction, result) => {
        if (result?.success) {
          this.close();
        }
        this.executingAction = false;
      }
    );
  }
}
