#include "SampleTable.h"
#include "ButtonEditor.h"
#include <QMenu>
#include <QAction>
#include <QIcon>

SampleTable::SampleTable(QWidget * parent)
 : QTableWidget(parent), button_editor(NULL) {

   InitTable();
}

SampleTable::SampleTable(int rows, int columns, QWidget * parent)
 : QTableWidget(rows, columns, parent), button_editor(NULL) {

   InitTable();
}

SampleTable::~SampleTable() {
}

void
SampleTable::SetButtonEditor(ButtonEditor * new_button_editor) {
   button_editor = new_button_editor;
}

void
SampleTable::customContextMenuRequested(const QPoint& pos) {
   QTableWidgetItem * item = itemAt(pos);
   if (item != NULL) {
      context_row = item->row();
      context_col = item->column();
      getContextMenu()->exec(mapToGlobal(pos));
   }
}

void
SampleTable::doSend() {
   setCurrentCell(context_row, context_col);
   if (button_editor != NULL) {
      button_editor->doSend();
   }
}

void
SampleTable::doDelete() {
   setCurrentCell(context_row, context_col);
   if (button_editor != NULL) {
      button_editor->doDeleteSample(true);
   }
}

void
SampleTable::InitTable() {
   ctx_menu = NULL;

   setContextMenuPolicy(Qt::CustomContextMenu);

   connect(this, SIGNAL(customContextMenuRequested(const QPoint&)),
           this, SLOT(customContextMenuRequested(const QPoint&)));
}

QMenu *
SampleTable::getContextMenu() {
   if (ctx_menu == NULL) {
      ctx_menu = new QMenu("Sample Actions", this);
      QIcon send_icon;
      send_icon.addFile(":/new/prefix1/images/remote.png");
      send_act = new QAction(send_icon, "Send Sample", this);
      ctx_menu->addAction(send_act);
      connect(send_act, SIGNAL(triggered(bool)), this, SLOT(doSend()));
      QIcon del_icon;
      del_icon.addFile(":/new/prefix1/images/delete-button.png");
      delete_act = new QAction(del_icon, "Delete Sample", this);
      ctx_menu->addAction(delete_act);
      connect(delete_act, SIGNAL(triggered(bool)), this, SLOT(doDelete()));
   }
   send_act->setEnabled((button_editor != NULL) &&
                        (button_editor->RemoteDeviceIsOpen()));
   return ctx_menu;
}
