#include "input_initial_state.hpp"

QtInputInitialState::QtInputInitialState(InitialState* _initial_state):QWidget(){
  initial_state=_initial_state;

  main_layout=new QVBoxLayout;
  tanks_layout=new QVBoxLayout;
  button_layout=new QHBoxLayout;
  tanks_widget=new QWidget;
  button_widget=new QWidget;
  scroll_area=new QScrollArea;
  add_button=new QPushButton("Add tank");
  refresh_button=new QPushButton("Refresh");

  tanks_widget->setLayout(tanks_layout);
  scroll_area->setWidget(tanks_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,&QtInputInitialState::addTank);
  connect(refresh_button,&QPushButton::clicked,this,&QtInputInitialState::updateInitialState);
}

void
QtInputInitialState::addTank(){
  QtInputTank* input_tank=new QtInputTank(initial_state);
  tanks_layout->addWidget(input_tank);
  connect(input_tank,&QtInputTank::remove,this,&QtInputInitialState::removeTank);
  emit initialStateChanged();
}

void
QtInputInitialState::removeTank(QtInputTank* input_tank){
  disconnect(input_tank,nullptr,nullptr,nullptr);
  tanks_layout->removeWidget(input_tank);
  delete input_tank;
  emit initialStateChanged();
}

QWidget*
QtInputInitialState::validate(){
  for(size_t i=0;i<tanks_layout->count();++i){
    QtInputTank* tank_input=(QtInputTank*)tanks_layout->itemAt(i)->widget();
    QWidget* widget=tank_input->validate();
    if(widget!=nullptr) return widget;
  }
  return nullptr;
}
void
QtInputInitialState::updateInitialState(){
  QWidget* widget=validate();
  if(widget!=nullptr){
    QMessageBox msgBox;
    msgBox.setText("Incorrect tank entry");
    msgBox.exec();
    widget->setFocus();
  }
  emit initialStateChanged();
}

void
QtInputInitialState::save(fstream& file){
  double d;
  size_t n;
  //d=lX_input->text().toDouble();
  //file.write((char*)&d,sizeof(double));
}
