#include "model.hpp"
#include "protocols.hpp"

Model::Model(const ProtocolSource source)
    : searchFilter(""), supportFilter(ALL), filteredModel(&supportModel),
      name(QString::fromStdString(source_to_string(source))), includeStatus(source == UPSTREAM),
      includeName(source != UNKNOWN) {
    searchModel.setSourceModel(&sourceModel);
    searchModel.setFilterKeyColumn(-1);
    searchModel.setFilterCaseSensitivity(Qt::CaseInsensitive);

    supportModel.setSourceModel(&searchModel);
    supportModel.setFilterRole(Qt::UserRole);

    if (includeStatus) {
        sourceModel.setHorizontalHeaderLabels({"Status", "Name", "Identifier", "Interface Version"});
        sourceModel.horizontalHeaderItem(0)->setToolTip("The stability level of the protocol");
        sourceModel.horizontalHeaderItem(1)->setToolTip("The human-readable name of the protocol");
        sourceModel.horizontalHeaderItem(2)->setToolTip("The full name of the protocol's upstream XML representation");
        sourceModel.horizontalHeaderItem(3)->setToolTip(
            "The version of the protocol's interface that's implemented by the compositor");
    } else if (includeName) {
        sourceModel.setHorizontalHeaderLabels({"Name", "Identifier", "Interface Version"});
        sourceModel.horizontalHeaderItem(0)->setToolTip("The human-readable name of the protocol");
        sourceModel.horizontalHeaderItem(1)->setToolTip("The full name of the protocol's upstream XML representation");
        sourceModel.horizontalHeaderItem(2)->setToolTip(
            "The version of the protocol's interface that's implemented by the compositor");
    } else {
        sourceModel.setHorizontalHeaderLabels({"Interface Identifier", "Interface Version"});
        sourceModel.horizontalHeaderItem(0)->setToolTip("The identifier reported by the compositor for this interface");
        sourceModel.horizontalHeaderItem(1)->setToolTip("The version of the interface that's implemented by the compositor");
    }
}

Model::~Model() = default;

void Model::setSearchFilter(const QString& newSearchFilter) {
    this->searchFilter = newSearchFilter;
    searchModel.setFilterFixedString(newSearchFilter);
    updateFilter();
}

void Model::setSupportFilter(const SupportFilters newSupportFilter) {
    this->supportFilter = newSupportFilter;
    switch (newSupportFilter) {
        default:
        case ALL:
            supportModel.setFilterFixedString("");
            break;
        case SUPPORTED:
            supportModel.setFilterFixedString("true");
            break;
        case UNSUPPORTED:
            supportModel.setFilterFixedString("false");
            break;
    }
    updateFilter();
}

void Model::updateFilter() {
    emit filterChanged(!searchFilter.isEmpty() || supportFilter != ALL);
}
