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

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

@Component({
  selector: 'bci-chip',
  templateUrl: './chip.component.html',
  styleUrls: ['./chip.component.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush,
})
export class BciChipComponent {
  @HostBinding('class.bci-chip') private addBciChipClass = true;

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

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

  /**
   * Flag to indicate whether the remove-icon is being displayed
   */
  @Input() removable = true;

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

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

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

  /**
   * Tooltip text which is updated when this element is hovered
   */
  protected cachedMatTooltipText: string = '';

  /**
   * Show the projected content inside a tooltip or not
   */
  protected showTooltip = false;

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

  /**
   * Make sure a tooltip is shown if the ng-content text overflows
   */
  @HostListener('mouseenter') private updateTooltip() {
    if (!this.contentRef) return;
    this.showTooltip = this.isTextOverflow(this.contentRef.nativeElement);
    this.cachedMatTooltipText = this.matTooltipText;
    this.changeDetector.markForCheck();
  }

  /**
   * Chip tooltip text
   */
  get matTooltipText(): string {
    return (this.contentRef?.nativeElement.textContent || '').trim();
  }

  /**
   * // 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
   */
  private 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;
  }
}
