#include "input_clouds_tab.hpp"

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

  main_layout=new QVBoxLayout;
  clouds_layout=new QVBoxLayout;
  button_layout=new QHBoxLayout;
  clouds_widget=new QWidget;
  button_widget=new QWidget;
  scroll_area=new QScrollArea;
  add_button=new QPushButton("Add cloud");
  refresh_button=new QPushButton("Refresh");

  clouds_widget->setLayout(clouds_layout);
  scroll_area->setWidget(clouds_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,&QtInputCloudsTab::addCloud);
  connect(refresh_button,&QPushButton::clicked,this,&QtInputCloudsTab::updateSources);
}

void
QtInputCloudsTab::addCloud(){
  QtInputCloud* input_cloud=new QtInputCloud(source);
  clouds_layout->addWidget(input_cloud);
  connect(input_cloud,&QtInputCloud::remove,this,&QtInputCloudsTab::removeCloud);
  emit sourcesChanged();
}

void
QtInputCloudsTab::removeCloud(QtInputCloud* input_cloud){
  disconnect(input_cloud,nullptr,nullptr,nullptr);
  clouds_layout->removeWidget(input_cloud);
  delete input_cloud;
  emit sourcesChanged();
}

QWidget*
QtInputCloudsTab::validate(){
  for(size_t i=0;i<clouds_layout->count();++i){
    QtInputCloud* cloud_input=(QtInputCloud*)clouds_layout->itemAt(i)->widget();
    QWidget* widget=cloud_input->validate();
    if(widget!=nullptr) return widget;
  }
  return nullptr;
}

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