#include "qgui.h"

const int AlignRight = Qt::AlignRight | Qt::AlignVCenter;

Table::Table(std::initializer_list<ColAttr> colAttrs, int rows, QWidget *parent) : NumTable{rows, (int)colAttrs.size(), parent} {
    int i = 0;
    for(typename std::initializer_list<ColAttr>::const_iterator it = colAttrs.begin(); it != colAttrs.end(); ++it) {
        auto item = horizontalHeaderItem(i);
        if(item==0) setHorizontalHeaderItem(i, item = new QTableWidgetItem());
        item->setText(it->text);
        item->setData(0x99, it->width);
        if(it->width > 0) horizontalHeader()->resizeSection(i, it->width);
        if(it->resizeMode > -1) horizontalHeader()->setSectionResizeMode(i, (QHeaderView::ResizeMode)it->resizeMode);
        mFieldMap.insert(it->field, i++);
    }
}

int Table::sizeHintForColumn(int column) const {
    auto item = horizontalHeaderItem(column);
    if(item==0) return QTableWidget::sizeHintForColumn(column);
    int width = item->data(0x99).toInt();
    if(width==0) return QTableWidget::sizeHintForColumn(column);
    auto header = horizontalHeader();
    if(header->sectionResizeMode(column) != QHeaderView::ResizeToContents) return QTableWidget::sizeHintForColumn(column);
    int colCnt = columnCount();
    int remainWidth = header->width(), stretchWidth = width;
    for(int cc=0; cc<colCnt; cc++) if(cc!=column && (item = horizontalHeaderItem(cc))) {
        if(header->sectionResizeMode(cc) == QHeaderView::ResizeToContents) stretchWidth += item->data(0x99).toInt();
        else remainWidth -= item->data(0x99).toInt();
    }
    if(remainWidth<=0) return QTableWidget::sizeHintForColumn(column);
    return width * remainWidth / stretchWidth;
}
