import Columns from './Columns';

class TableModel {
  constructor(columns, rows) {
    this.columns = columns; // Array of Columns objects
    this.rows = rows;
  }

  updateRows(newRows) {
    this.rows = newRows;
  }
}

class TableView {
  constructor(model) {
    this.model = model;
    this.table = document.createElement('table');
    this.table.style.border = '1px solid black';
    this.tbody = document.createElement('tbody'); // Keep tbody as a member for updates
    this.table.appendChild(this.renderTableHeader());
    this.table.appendChild(this.tbody); // Append tbody to the table
  }

  render() {
    this.renderTableBody(); // Initial rendering of the table body
    return this.table;
  }

  renderTableHeader() {
    const thead = document.createElement('thead');
    const tr = document.createElement('tr');
    thead.appendChild(tr);

    this.model.columns.getColumns().forEach(column => {
      tr.appendChild(column.renderHeader());
    });

    return thead;
  }

  renderTableBody() {
    // Clear existing tbody content
    while (this.tbody.firstChild) {
      this.tbody.removeChild(this.tbody.firstChild);
    }

    // Populate tbody with new rows
    this.model.rows.forEach(row => {
      const tr = document.createElement('tr');
      this.model.columns.getColumns().forEach(column => {
        tr.appendChild(column.renderCell(row[column.header]));
      });
      this.tbody.appendChild(tr);
    });
  }
}

class TableController {
  constructor(model) {
    this.model = model;
    this.view = new TableView(this.model);
  }

  updateView() {
    const tableDiv = document.getElementById('tableDiv');
    // Clear the previous table view
    while (tableDiv.firstChild) {
      tableDiv.removeChild(tableDiv.firstChild);
    }
    tableDiv.appendChild(this.view.render());
  }

  updateRows(newRows) {
    this.model.updateRows(newRows);
    this.view.renderTableBody(); // Re-render the table body
  }
}

class Table {
  constructor(columnJson) {
    const columns = new Columns(columnJson);
    this.model = new TableModel(columns, []);
    this.controller = new TableController(this.model);
  }

  updateRows(data) {
    this.controller.updateRows(data);
  }
}

export default Table;
