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

import { Component, ElementRef, EventEmitter, Input, Output, Renderer2 } from '@angular/core';
import { ResizeHandleSizeChangedEvent } from '../../resize-handle/resize-handle.model';

/**
 * A splitter area component defines a space that can be resized using a resize handle.
 * This area is a child of the `bci-splitter` component
 * This component is a POC. Is subject to changes, use it with care.
 * To be used as `<bci-splitter><bci-splitter-area></bci-splitter-area></bci-splitter>`
 */
@Component({
  selector: 'bci-splitter-area',
  templateUrl: './splitter-area.component.html',
  styleUrls: ['./splitter-area.component.scss'],
})
export class SplitterAreaComponent {
  private _sizePx: number;

  /**
   * Internal attribute to show the resizer.
   */
  hasResizer = true;

  /**
   * Gets or sets the area size in pixels as number.
   */
  get sizePx(): number {
    return this._sizePx;
  }

  set sizePx(value: number) {
    this._sizePx = value;
    this.setSize();
  }

  /**
   * Gets or sets the area size as string, eg: 100px.
   */
  @Input()
  get size(): string {
    return this.sizePx === undefined ? undefined : `${this.sizePx}px`;
  }

  set size(value: string) {
    this.sizePx = value === undefined ? undefined : parseFloat(value);
    this.setSize();
  }

  @Output() resized: EventEmitter<void> = new EventEmitter();

  constructor(private elRef: ElementRef, private renderer: Renderer2) {}

  resizerChanged($event: ResizeHandleSizeChangedEvent) {
    this.sizePx = $event.value;
    this.setSize();
    this.resized.emit();
  }

  private setSize() {
    if (this.sizePx) {
      this.renderer.setStyle(this.elRef.nativeElement, 'flex', `1 1 ${this.size}`);
      this.renderer.setStyle(this.elRef.nativeElement, 'max-width', `${this.size}`);
    } else {
      this.renderer.setStyle(this.elRef.nativeElement, 'flex', '1 1 auto');
      this.renderer.setStyle(this.elRef.nativeElement, 'max-width', `unset`);
    }
  }
}
