//
// Created by Krad on 2021/11/23.
//

#include <QtCore/QFile>
#include <QtCore/QTextStream>
#include "LogFileTableModel.h"
#include <QDebug>

LogFileTableModel::LogFileTableModel(QObject *parent) : QAbstractTableModel(parent) {

}

void LogFileTableModel::setFileName(QString fileName) {
    if (!logdata.isEmpty())logdata.clear();
    qDebug()<<fileName;
    QFile f;
    f.setFileName(fileName);
    if (!f.exists()) return;
    if(f.open(QFile::OpenModeFlag::ReadOnly | QFile::OpenModeFlag::Text))
    {

        QTextStream in(&f);
        while(!in.atEnd()){
            logdata.push_back(in.readLine().split("\t"));
        }
    }
}

QVariant LogFileTableModel::data(const QModelIndex &index, int role) const {
    if (!index.isValid()) return QVariant();
    if (role == Qt::TextAlignmentRole) {
        return Qt::AlignCenter;
    }
    if (role == Qt::DisplayRole || role == Qt::EditRole )
    {
        return logdata[index.row()][index.column()];
    }
    return QVariant();
}

int LogFileTableModel::rowCount(const QModelIndex &parent) const {
    if (!logdata.isEmpty()) return logdata.count();
    return 0;
}

int LogFileTableModel::columnCount(const QModelIndex &parent) const {
    if (!logdata.isEmpty()) return logdata[0].count();
    return 0;
}

QVariant LogFileTableModel::headerData(int section, Qt::Orientation orientation, int role) const {
    if(role != Qt::DisplayRole)
        return QVariant();
    if(orientation == Qt::Horizontal)
        return headerStrings.at(section);
    return QVariant();
}
