#include "input_pump_tab.hpp"

QtInputPumpTab::QtInputPumpTab(Source* _source):QWidget(){
  source=_source;

  main_layout=new QVBoxLayout;
  pumps_layout=new QVBoxLayout;
  button_layout=new QHBoxLayout;
  pumps_widget=new QWidget;
  button_widget=new QWidget;
  scroll_area=new QScrollArea;
  add_button=new QPushButton("Add pump");
  refresh_button=new QPushButton("Refresh");

  pumps_widget->setLayout(pumps_layout);
  scroll_area->setWidget(pumps_widget);
  scroll_area->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
  scroll_area->setWidgetResizable(true);
  main_layout->addWidget(scroll_area);

  button_layout->addWidget(add_button);
  button_layout->addWidget(refresh_button);
  button_widget->setLayout(button_layout);
  main_layout->addWidget(button_widget);

  setLayout(main_layout);
  connect(add_button,&QPushButton::clicked,this,&QtInputPumpTab::addPump);
  connect(refresh_button,&QPushButton::clicked,this,&QtInputPumpTab::updateSources);
}

void
QtInputPumpTab::addPump(){
  QtInputPump* input_pump=new QtInputPump(source);
  pumps_layout->addWidget(input_pump);
  connect(input_pump,&QtInputPump::remove,this,&QtInputPumpTab::removePump);
  emit sourcesChanged();
}

void
QtInputPumpTab::removePump(QtInputPump* input_pump){
  disconnect(input_pump,nullptr,nullptr,nullptr);
  pumps_layout->removeWidget(input_pump);
  delete input_pump;
  emit sourcesChanged();
}

QWidget*
QtInputPumpTab::validate(){
  for(size_t i=0;i<pumps_layout->count();++i){
    QtInputPump* pump_input=(QtInputPump*)pumps_layout->itemAt(i)->widget();
    QWidget* widget=pump_input->validate();
    if(widget!=nullptr) return widget;
  }
  return nullptr;
}

void
QtInputPumpTab::updateSources(){
  QWidget* widget=validate();
  if(widget!=nullptr){
    QMessageBox msgBox;
    msgBox.setText("Incorrect pump entry");
    msgBox.exec();
    widget->setFocus();
  }
  emit sourcesChanged();
}
