//
// 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 "Store.hpp"
#include "Stack.hpp"

#include <QFileInfo>
#include "Information.hpp"
#include <string.h>
#include "Dir.hpp"
#include <climits>

namespace mgx 
{
  Store::Store(Stack* stack) : _label(false), changed_function(false), _opacity(1.0f),
                          _brightness(1.0f), _changed(), _isVisible(false), _stack(stack) {}
  
  Store::Store(const Store& copy) : _label(copy._label), changed_function(false), 
    _opacity(copy._opacity), _brightness(copy._brightness), _changed(), 
  	_isVisible(copy._isVisible), _stack(copy._stack) {}
  
  Store::~Store() { _data.clear(); }
  
  void Store::allocate()
  {
    Point3u size = _stack->size();
    size_t s = size_t(size.x()) * size.y() * size.z();
  
    _data.resize(s);
  }
  
  void Store::reset()
  {
    allocate();
    setFile();
    memset(_data.data(), 0, _data.size() * sizeof(ushort));
  }
  
  void Store::copyMetaData(const Store* other)
  {
    if(other != this) {
      setFile(other->file());
      setLabels(other->labels());
    }
  }
  
  void Store::setFile(const QString& file)
  {
    if(file.isEmpty()) {
      _filename = file;
    } else {
      _filename = absoluteFilePath(file);
    }
  }
  
  void Store::resetModified()
  {
    changed_function = false;
    _changed = BoundingBox3i();
  }
  
  void Store::setStack(Stack* s) {
    _stack = s;
  }
  
  void Store::changed() {
    _changed = _stack->boundingBox();
  }
  
  void swapMetaData(Store* s1, Store* s2)
  {
    if(s1 == s2)
      return;
    // Labels
    bool l1 = s1->labels();
    s1->setLabels(s2->labels());
    s2->setLabels(l1);
  
    // Files
    QString f1 = s1->file();
    s1->setFile(s2->file());
    s2->setFile(f1);
  }
}
