
#include "ads_rawmsgwidget.h"

#include <QLineEdit>


AdsRawSpinBox16::AdsRawSpinBox16(Ads1553MsgQ** m, int w, QWidget* parent):
  QSpinBox(parent),
  msg(m),
  word(w)
{
  int x=0x10000;

  validator = new QRegExpValidator(QRegExp("[0-9A-Fa-f]{1,8}"), this);

  setRange(-0x10000, x);
  setSizePolicy(QSizePolicy(QSizePolicy::Fixed,QSizePolicy::Fixed));
  setKeyboardTracking(false);
  base=10;
  cache=0;
  setValue(0);

  connect(this, SIGNAL(valueChanged(int)), SLOT(setMsgValue(int)));
}

void AdsRawSpinBox16::decMode()
{
  hexMode(false);
}

void AdsRawSpinBox16::hexMode(bool h)
{
  int v=value();
  /*
  if (h)
  {
    lineEdit()->setInputMask(QString("hhhh"));
    base=16;
  }
  else
  {
    lineEdit()->setInputMask(defaultIMask);
    base=10;
  }
  */
  blockSignals(true);
  base=h ? 16 : 10;
  clear();
  setValue(v);
  blockSignals(false);
}

void AdsRawSpinBox16::setMsgValue(int val)
{
  avb_1553_word_t v=avb_1553_word_t(val);
  if (*msg)
  {
    if ((*msg)->data(word)!=v)
      (*msg)->setData(word, val);
  }
}

QString AdsRawSpinBox16::textFromValue(int value) const
{
    if (base==16)
      return QString().number(value, base).toUpper();
    else
      return QSpinBox::textFromValue(value);
}

int AdsRawSpinBox16::valueFromText(const QString& text) const
{
   if (base==16)
      return text.toInt(0, base);
   else
     return QSpinBox::valueFromText(text);
}

QValidator::State AdsRawSpinBox16::validate ( QString & input, int & pos ) const
{
  if (base==16)
    return validator->validate(input, pos);
  else
    return QValidator::Acceptable;
}


void AdsRawDataView::initialize(QWidget* parent)
{
  for(int i=0; i<32; ++i)
  {
    wRawData[i]=new AdsRawSpinBox16(&rawCurrentMsg, i, parent);
    wRawData[i]->setDisabled(true);
  }
  rawCurrentMsg=0;
}

void AdsRawDataView::connect(Ads1553MsgQ* m)
{
  if  (rawCurrentMsg)
    rawCurrentMsg->messageModified.disconnect(this);
  rawCurrentMsg=m;
  unsigned int wc=0;
  bool ro=true;

  if (rawCurrentMsg)
  {
    wc=m->wordCount();
    ro=m->isReadOnly();
  }

  for(unsigned int i=0; i<wc; ++i)
  {
    wRawData[i]->clear();
    wRawData[i]->setDisabled(ro);
  }
  for(unsigned int i=wc; i<32; ++i)
  {
    wRawData[i]->clear();
    wRawData[i]->setDisabled(true);
  }

  force_update=true;

  onMessageUpdated(m);

  if (rawCurrentMsg)
    rawCurrentMsg->messageModified.ads_connect(this, onMessageUpdated);
}

void AdsRawDataView::setHexMode(bool hex)
{
  for(unsigned int i=0; i<32; ++i)
  {
    wRawData[i]->hexMode(hex);
  }
}

ADS_SLOT_IMPLEMENT(AdsRawDataView, onMessageUpdated, (Ads1553MsgQ* m), (m))
{
  if (!m)
    return;

  unsigned int wc=m->wordCount();
  for(unsigned int i=0; i<wc; ++i)
  {
    avb_1553_word_t v=m->data(i);

    if (force_update || cache.data[i]!=v)
    {
      wRawData[i]->setValue(v);
      cache.data[i]=v;
    }
  }
  force_update=false;
}

