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

import { AfterContentInit, Component, ContentChildren, EventEmitter, Input, Output, QueryList } from '@angular/core';
import { CommandbarSidebarSlideComponent } from './commandbar-sidebar-slide.component';

@Component({
  selector: 'bci-commandbar-sidebar',
  templateUrl: './commandbar-sidebar.component.html',
  styleUrls: ['./commandbar-sidebar.component.scss'],
})
export class CommandbarSidebarComponent implements AfterContentInit {
  /**
   * Event emitter for when the sidebar has been closed.
   */
  @Output() closed = new EventEmitter<void>();

  /**
   * Event emitter for when the sidebar is being opened.
   */
  @Output() opening = new EventEmitter<void>();
  @ContentChildren(CommandbarSidebarSlideComponent) slides: QueryList<CommandbarSidebarSlideComponent>;
  private _opened = false;
  private _activeSlide: string;

  /**
   * Whether sidebar is openend or not.
   */
  get opened(): boolean {
    return this._opened;
  }

  /**
   * Set whether the sidebar should be opened.
   */
  @Input()
  set opened(shouldBeOpen: boolean) {
    if (shouldBeOpen !== this._opened) {
      if (this._opened) {
        this._opened = false;
        this.closed.emit();
      } else {
        this._opened = true;
        this.opening.emit();
      }
    }
  }

  /**
   * The current slide's key.
   */
  get activeSlide(): string {
    return this._activeSlide;
  }

  /**
   * Set the current slide's key.
   */
  set activeSlide(key: string) {
    this._activeSlide = key;
    this.slides.forEach((slide) => (slide.active = this._activeSlide === slide.key));
  }

  ngAfterContentInit() {
    this.activeSlide = undefined;
  }
}
