//
// This file is part of MorphoGraphX - http://www.MorphoGraphX.org
// Copyright (C) 2012-2015 Richard S. Smith and collaborators.
//
// If you use MorphoGraphX in your work, please cite:
//   http://dx.doi.org/10.7554/eLife.05864
//
// MorphoGraphX is free software, and is licensed under under the terms of the 
// GNU General (GPL) Public License version 2.0, http://www.gnu.org/licenses.
// 
#include "EditMarkersDlg.hpp"

namespace mgx 
{
  
  EditMarkersDlg::EditMarkersDlg(const TransferFunction& fct, QWidget* parent, Qt::WindowFlags f)
    : QDialog(parent, f), function(fct)
  {
    ui.setupUi(this);
    std::vector<double> markers(fct.size());
    std::vector<QColor> colors(fct.size());
    for(size_t i = 0; i < fct.size(); ++i) {
      double pos = fct[i];
      QColor col = fct.rgba_point(pos);
      markers[i] = pos;
      colors[i] = col;
    }
    bool showRgba = fct.interpolation() == TransferFunction::RGB;
    model = new TransferMarkerModel(markers, colors, fct.interpolation(), showRgba, this);
    ui.markersView->setModel(model);
    delegate = new MarkerColorDelegate(this);
    ui.markersView->setItemDelegate(delegate);
    spread_button = ui.buttonBox->addButton("Spread markers", QDialogButtonBox::ActionRole);
    connect(spread_button, SIGNAL(clicked()), this, SLOT(spreadMarkers()));
    ui.markersView->horizontalHeader()->setSectionResizeMode(1, QHeaderView::Stretch);
    ui.markersView->resizeColumnToContents(0);
    if(showRgba)
      ui.rgbaMode->setChecked(true);
    else
      ui.hsvaMode->setChecked(true);
  }
  
  void EditMarkersDlg::on_addMarker_clicked() {
    model->addMarker(ui.markersView->selectionModel()->selection());
  }
  
  void EditMarkersDlg::on_removeMarker_clicked() {
    model->removeMarker(ui.markersView->selectionModel()->selection());
  }
  
  void EditMarkersDlg::on_rgbaMode_toggled(bool on)
  {
    if(on)
      model->rgbaMode();
  }
  
  void EditMarkersDlg::on_hsvaMode_toggled(bool on)
  {
    if(on)
      model->hsvaMode();
  }
  
  void EditMarkersDlg::spreadMarkers() {
    model->spreadMarkers(ui.markersView->selectionModel()->selection());
  }
  
  EditMarkersDlg::value_list EditMarkersDlg::pointList() const
  {
    const std::vector<double>& markers = model->getMarkers();
    const std::vector<QColor>& colors = model->getColors();
    value_list lst(markers.size());
    Interpolation mode = function.interpolation();
    for(size_t i = 0; i < markers.size(); ++i) {
      double pos = markers[i];
      QColor c = colors[i];
      Colorf col;
      if(mode == TransferFunction::RGB)
        col = Colorf(c.redF(), c.greenF(), c.blueF(), c.alphaF());
      else
        col = Colorf(c.hueF() * 360, c.valueF(), c.saturationF(), c.alphaF());
      lst[i] = std::make_pair(pos, col);
    }
    return lst;
  }
}
