import { IObjectController } from './interfaces/object-controller';
import { IBaseFleioObjectModel } from '@fleio-api/base-model/base-fleio-object.model';
import { IDetailsData } from './interfaces/details/details-data';
import { BehaviorSubject, Observable, of } from 'rxjs';
import { CallbackAction } from './actions/callback-action';
import { IActionResult } from './interfaces/actions/action-result';
import { ISummaryCardData } from './interfaces/card-data/summary-card-data';
import { IPermissionsModel } from '@shared/fleio-api/base-model/IPermissionsModel';
import { IAction } from '@objects-view/interfaces/actions/action';

export class StaticObjectController implements IObjectController {
  object: IBaseFleioObjectModel;
  additionalObjects: { [objectName: string]: any };
  public currentTabIndex = new BehaviorSubject<number>(0);
  public currentTabIndex$ = this.currentTabIndex.asObservable();
  permissions: IPermissionsModel;

  dataChanged$ = null;
  actionCallback: (action: CallbackAction) => Observable<IActionResult> = null;
  detailsData: IDetailsData;
  readonly state: string;

  constructor(
    detailsData: IDetailsData,
    object?: IBaseFleioObjectModel,
    additionalObjects?: { [objectName: string]: any },
  ) {
    this.detailsData = detailsData || {tabs: []};
    if (this.detailsData?.detailsActions) {
      this.detailsData.detailsActions = this.setActionCallback(this.detailsData.detailsActions);
    }

    this.object = object ? object : {};
    this.additionalObjects = additionalObjects;
  }

  setActionCallback(actions: IAction[]): IAction[] {
    for (const action of actions) {
      if (action instanceof CallbackAction && !action.callback) {
        (action as CallbackAction).callback = (callbackAction) => {
          if (this.actionCallback) {
            return this.actionCallback(callbackAction);
          }

          return of(null);
        };
      }
    }

    return actions;
  }

  getDetailsCardData(): IDetailsData {
    return this.detailsData;
  }

  getSummaryCardData(): ISummaryCardData {
    return null;
  }
}
