import styles from '!raw-loader!sass-loader!./styles/app-price-table.scss';

class AppPriceTable extends HTMLElement {
	constructor() {
		super();
	}

	connectedCallback() {
		fetch(this.dataset.content)
			.then(response => response.json())
			.then(data => {
				const root = this.attachShadow({ mode: 'open' });

				const style = document.createElement('style');
				style.textContent = styles;
				root.appendChild(style);

				const table = document.createElement('table');
				table.className = 'table';
				table.cellSpacing = 0;

				const thead = document.createElement('thead');

				const theadRow = document.createElement('tr');

				data.columns.forEach(column => {
					const col = document.createElement('th');
					col.innerText = column;
					theadRow.appendChild(col);
				});

				thead.appendChild(theadRow);
				table.appendChild(thead);

				const tbody = document.createElement('tbody');

				data.data.forEach(item => {
					const row = document.createElement('tr');

					item.forEach((field, i) => {
						const cell = document.createElement('td');
						cell.innerText = field + ' ' + data.units[i];
						row.appendChild(cell);
					});

					tbody.appendChild(row);
				});

				table.appendChild(tbody);

				root.appendChild(table);
			});
	}

	static get observedAttributes() {
		return ['data-content'];
	}
}

customElements.define('app-price-table', AppPriceTable);
