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

import { AfterViewInit, ChangeDetectorRef, Component, ElementRef, EventEmitter, HostBinding, Input, Output, ViewChild } from '@angular/core';
import { BciSharedIntl } from '../shared-intl';

@Component({
  selector: 'bci-chip-selectable',
  templateUrl: './chip-selectable.component.html',
  styleUrls: ['./chip-selectable.component.scss'],
})
export class BciChipSelectableComponent implements AfterViewInit{
  @HostBinding('class.bci-chip') true;

  /**
   * The event emitter to propagate the selection-change-event
   */
   @Output() selectionChange: EventEmitter<any> = new EventEmitter();

  /**
   * Flag to indicate whether the chip is selected
   */
  @Input() selected = false;

  /**
   * Flag to indicate whether the chip is selectable
   */
  @Input() selectable = true;

  /**
   * Variable to hold the icon name
   */
  @Input() icon = '';

  /**
   * Variable to disable the chip
   */
  @Input() disabled = false;

  /**
   * refernces the chip projected content
   */
  @ViewChild('message', { static: true }) contentRef: ElementRef;

  /**
   * Variable to hold chip tooltip text
   */
  matTooltipText: string = '';

  constructor(public intl: BciSharedIntl, private cdr: ChangeDetectorRef) {}

  /**
   * // Determines if the passed element is overflowing its bounds,
  // either vertically or horizontally.
  // Will temporarily modify the "overflow" style to detect this
  // if necessary.
   * @param el html element of the chip label
   * @returns boolean
   */
  isTextOverflow(el: HTMLElement): boolean {
    const curOverflow = el.style.overflow;

    if (!curOverflow || curOverflow === "visible")
      el.style.overflow = "hidden";

    const isTextOverflow = el.clientWidth < el.scrollWidth
      || el.clientHeight < el.scrollHeight;

    el.style.overflow = curOverflow;

    return isTextOverflow;
  }

  ngAfterViewInit(): void {
    if (this.contentRef) {
      this.matTooltipText = this.contentRef.nativeElement.innerHTML;
      this.cdr.detectChanges();
    }
  }
}
