#include <stdio.h>
#include "RemoteTable.h"
#include <QStringList>
#include <QHeaderView>
#include <QMenu>
#include <QAction>
#include <QIcon>
#include <QDebug>
#include "OneButton.h"
#include "AardMain.h"
#include "ButtonEditor.h"

RemoteTable::RemoteTable(AardMain * init_mainwin)
 : QTableWidget(0, 3),
   appending_row(false),
   changing_row(false),
   in_do_item_changed(false),
   red_question(":/new/prefix1/images/red-question.png"),
   green_question(":/new/prefix1/images/green-question.png"),
   green_check(":/new/prefix1/images/green-check.png"),
   ctx_menu(NULL),
   mainwin(init_mainwin) {

   QStringList headers;
   headers << "Button" << "Status" << "Info";
   setHorizontalHeaderLabels(headers);
   horizontalHeader()->setStretchLastSection(true);
   verticalHeader()->hide();

   setContextMenuPolicy(Qt::CustomContextMenu);

   connect(this, SIGNAL(itemChanged(QTableWidgetItem *)), this,
           SLOT(doItemChanged(QTableWidgetItem *)));

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

   appendNewRow();
}

RemoteTable::~RemoteTable() {
   return;
}

void
RemoteTable::SetChangingRow(bool change_status) {
   changing_row = change_status;
}

void
RemoteTable::CheckLastRow() {
   if (rowCount() == 0) {
      appendNewRow();
   }
}

void
RemoteTable::CopyData() {
   int rows = rowCount();
   for (int r = 0; r < rows; ++r) {
      OneButton * obp = dynamic_cast<OneButton *>(item(r, 0));
      if (obp != NULL) {
         obp->CopyData();
      }
   }
}

void
RemoteTable::RestoreCopy() {
   int rows = rowCount();
   for (int r = 0; r < rows; ++r) {
      OneButton * obp = dynamic_cast<OneButton *>(item(r, 0));
      if (obp != NULL) {
         obp->RestoreCopy();
      }
   }
}

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

void
RemoteTable::doItemChanged(QTableWidgetItem * item) {
   if (in_do_item_changed ||
       appending_row ||
       (column(item) != 0) ||
       (item->text().isEmpty())) {
      return;
   }
   in_do_item_changed = true;

   // Make sure we have a legal button name, if not, fix it up.
   // (Legal -> no double quote chars, no duplicates).

   QString old_name = item->text();
   QString new_name = old_name;
   new_name.remove('\"');
   QString base_name = new_name;
   int unique = 2;
   for ( ; ; ) {
      int dups = CountDuplicates(new_name, item);
      if (dups > 0) {
         new_name = base_name;
         new_name.append(QString("<%1>").arg(unique++));
      } else {
         break;
      }
   }
   if (old_name != new_name) {
      item->setText(new_name);
   }

   if (row(item) == (rowCount() - 1)) {
      appendNewRow();
   }
   in_do_item_changed = false;
}

void
RemoteTable::doDetails() {
   OneButton * the_button =
      dynamic_cast<OneButton *>(item(context_row, 0));
   if (the_button != NULL) {
      mainwin->getButtonEditor()->doEditButton(the_button);
   }
}

void
RemoteTable::doDelete() {
   removeRow(context_row);
   CheckLastRow();
}

void
RemoteTable::appendNewRow() {
   appending_row = true;
   int rows = rowCount();
   insertRow(rows);
   OneButton * i = dynamic_cast<OneButton *>(item(rows, 0));
   if (i == NULL) {
      i = new OneButton;
      setItem(rows, 0, i);
      i->UpdateButtonInfo();
   }
   if (! changing_row) {
      selectRow(rows);
   }
   appending_row = false;
}

int
RemoteTable::CountDuplicates(QString txt, QTableWidgetItem * skip_item) {
   int dups = 0;
   int rows = rowCount();
   int skip_row = row(skip_item);
   for (int r = 0; r < rows; ++r) {
      if (r != skip_row) {
         QTableWidgetItem * itp = item(r, 0);
         if ((itp != NULL) && (txt == itp->text())) {
            ++dups;
         }
      }
   }
   return dups;
}

QMenu *
RemoteTable::getContextMenu() {
   if (ctx_menu == NULL) {
      ctx_menu = new QMenu("Button Actions", this);
      QIcon dtl_icon;
      dtl_icon.addFile(":/new/prefix1/images/button.png");
      details_act = new QAction(dtl_icon, "Button Details", this);
      ctx_menu->addAction(details_act);
      connect(details_act, SIGNAL(triggered(bool)), this, SLOT(doDetails()));
      QIcon del_icon;
      del_icon.addFile(":/new/prefix1/images/delete-button.png");
      delete_act = new QAction(del_icon, "Delete Button", this);
      ctx_menu->addAction(delete_act);
      connect(delete_act, SIGNAL(triggered(bool)), this, SLOT(doDelete()));
   }
   return ctx_menu;
}
