export interface ListItemValue {
  id: string;
  label: string;
  type: string;
  title: string;
  description: string;
  url: string;
}

import {Component, Element, h, Prop, Watch} from '@stencil/core';

@Component({
  tag: 'hy-general-list',
  styleUrl: 'hy-general-list.scss',
  shadow: true,
})
export class HyGeneralList {
  @Prop() dataItems: ListItemValue[] | string;
  private _dataItems: ListItemValue[];
  @Element() el: HTMLElement;

  @Watch('dataItems')
  arrayDataWatcher(newValue: ListItemValue[] | string) {
    if (typeof newValue === 'string') {
      this._dataItems = JSON.parse(newValue);
    } else {
      this._dataItems = newValue;
    }
  }

  componentWillLoad() {
    this.arrayDataWatcher(this.dataItems);
  }

  handleCardClick(id) {
    let card = this.el.shadowRoot.querySelectorAll('#' + id)[0] as HTMLElement;
    window.open(card.dataset.location, '_blank');
  }

  render() {
    const classAttributes = ['hy-general-list'].join(' ');

    return [
      <div class={classAttributes}>
        {this._dataItems.map((x) => {
          return [
            <hy-general-list-item
              id={x.id}
              item-title={x.title}
              description={x.description}
              label={x.label}
              url={x.url}
              type={x.type}
              data-location={x.url}
              onClick={() => this.handleCardClick(x.id)}
            ></hy-general-list-item>,
          ];
        })}
      </div>,
    ];
  }
}