#include "sqltablenoticedelegate.h"

#include "../databaseinfo/databaseinfo.h"

#include "../sqlscript/sqlscript.h"

#include <QPainter>

#include <QSqlTableModel>

#include <QApplication>

#include <QSqlRecord>

#include <QDebug>

SqlTableNoticeDelegate::SqlTableNoticeDelegate(QObject *parent)
    : QStyledItemDelegate(parent) {}

void SqlTableNoticeDelegate::refreshPainter(QPainter *painter,
                                            const QRect &rect,
                                            const QColor &borderColor) const {
  QColor background =
      qApp->palette("QTableView").color(QPalette::ColorRole::Background);
  background.setAlpha(0);
  QLinearGradient gradientRight(rect.topLeft(), rect.topRight());
  QLinearGradient gradientBottom(rect.topLeft(), rect.bottomLeft());
  QLinearGradient gradientLeft(rect.topRight(), rect.topLeft());
  QLinearGradient gradientTop(rect.bottomLeft(), rect.topLeft());
  for (auto *gradient :
       {&gradientRight, &gradientBottom, &gradientLeft, &gradientTop}) {
    gradient->setColorAt(0, background);
    gradient->setColorAt(1, borderColor);
  }
  double thickPercent = 2.0;
  double thickVertical = 1.0 - thickPercent / rect.width();
  double thickHorizontal = 1.0 - thickPercent / rect.height();
  gradientRight.setColorAt(thickVertical, background);
  gradientLeft.setColorAt(thickVertical, background);
  gradientBottom.setColorAt(thickHorizontal, background);
  gradientTop.setColorAt(thickHorizontal, background);

  painter->save();
  painter->fillRect(rect, gradientRight);
  painter->fillRect(rect, gradientLeft);
  painter->fillRect(rect, gradientTop);
  painter->fillRect(rect, gradientBottom);
  painter->restore();
}

void SqlTableNoticeDelegate::paint(QPainter *painter,
                                   const QStyleOptionViewItem &option,
                                   const QModelIndex &index) const {
  auto model = static_cast<const QSqlTableModel *>(index.model());
  if (model->isDirty(index)) {
    QColor borderColor = QColor::fromHsvF(30.0 / 360.0, 0.5, 1.0);
    refreshPainter(painter, option.rect, borderColor);
    QStyledItemDelegate::paint(painter, option, index);
    return;
  }
  if (index.data().isNull()) {
    QColor borderColor = QColor::fromHsvF(0.0, 0.5, 1.0);
    refreshPainter(painter, option.rect, borderColor);
    QStyledItemDelegate::paint(painter, option, index);
    return;
  }
  QStyledItemDelegate::paint(painter, option, index);
  return;
}
