import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
  name: 'descriptionText',
})
export class DescriptionTextPipe implements PipeTransform {
  transform(value: string): string {
    if (value !== null) {
      let shortenText = '';
      const container = document.getElementById('details-container');
      const el = document.getElementById('details-text');
      el.innerHTML = value;
      const wordArray = el.innerHTML.split(' ');

      if (el.offsetHeight > container.offsetHeight && !shortenText) {
        while (el.offsetHeight > container.offsetHeight + 2 && wordArray.length > 3) {
          wordArray.pop();
          el.innerHTML = wordArray.join(' ') + '...';
        }

        // check if last element has a break line
        if (wordArray[2]) {
          const firstBrOcurrance = wordArray[2].indexOf('<br>');
          wordArray[2] = wordArray[2].slice(0, wordArray[2].indexOf('<br>', firstBrOcurrance + 1));
        }

        // trim all elements
        for (let i = 0; i < 3; i++) {
          wordArray[i] = wordArray[i].trim();
        }

        // Make room for the more button
        if (el.offsetWidth + 30 > container.offsetWidth) {
          wordArray.pop();
          wordArray.pop();
        }
        shortenText = wordArray.join(' ') + '...';
        el.innerHTML = wordArray.join(' ') + '...';
      } else {
        el.innerHTML = shortenText;
      }
    } else {
      return '';
    }
  }
}
