/*
 * Copyright (C) 2018 Robert Bosch GmbH Copyright (C) 2018 Robert Bosch Manufacturing Solutions GmbH, Germany. All rights reserved.
 */

import { Injectable } from '@angular/core';
import { BehaviorSubject, map, skip } from 'rxjs';
import { Widget } from '../models/widget';

import { PinboardGridComponent } from '../pinboard-grid/pinboard-grid.component';

@Injectable({ providedIn: 'root' })
/**
 * Handle pinboard interactions
 */
export class PinboardInteractionService {
  private pinboardGridComponentSubject = new BehaviorSubject<PinboardGridComponent | undefined>(undefined);
  /**
   * Holds the PinboardGridComponent
   */
  public readonly pinboardGridComponent$ = this.pinboardGridComponentSubject.pipe(skip(1));
  public readonly widgets$ = this.pinboardGridComponent$.pipe(map(comp => comp.getWidgets()))

  public setPinboardGridComponent(item: PinboardGridComponent): void {
    this.pinboardGridComponentSubject.next(item);
  }

  /**
   * checks for collisions, resizes the passed widget and updates the grid
   * @param widget
   * @returns true if the action was successful
   */
  public handleWidgetResize(widget: Widget): boolean {
    const comp = this.pinboardGridComponentSubject.value;
    if (!comp) {
      return false;
    }
    comp.checkForWidgetCollision(widget);
    comp.resizeWidgets();
    comp.updateGrid();
    return true;
  }
}
