#include "WimaServiceArea.h"

const char *WimaServiceArea::wimaServiceAreaName = "Service Area";

WimaServiceArea::WimaServiceArea(QObject *parent) : WimaArea(parent) { init(); }

WimaServiceArea::WimaServiceArea(const WimaServiceArea &other, QObject *parent)
    : WimaArea(other, parent) {
  init();
}

/*!
 * \overload operator=()
 *
 * Calls the inherited operator WimaArea::operator=().
 */
WimaServiceArea &WimaServiceArea::operator=(const WimaServiceArea &other) {
  WimaArea::operator=(other);

  return *this;
}

bool WimaServiceArea::setDepot(const QGeoCoordinate &coordinate) {
  if (_depot != coordinate) {
    if (this->containsCoordinate(coordinate)) {
      _depot = coordinate;
      emit depotChanged();
      return true;
    }
  }
  return false;
}

void WimaServiceArea::saveToJson(QJsonObject &json) {
  this->WimaArea::saveToJson(json);
  json[areaTypeName] = wimaServiceAreaName;
}

bool WimaServiceArea::loadFromJson(const QJsonObject &json,
                                   QString &errorString) {
  if (this->WimaArea::loadFromJson(json, errorString)) {
    bool retVal = true;
    // code for loading here
    return retVal;
  } else {
    qWarning() << errorString;
    return false;
  }
}

void print(const WimaServiceArea &area) {
  QString message;
  print(area, message);
  qWarning() << message;
}

void print(const WimaServiceArea &area, QString &outputStr) {
  print(static_cast<const WimaArea &>(area), outputStr);
  outputStr.append(QString("Depot Position: %s\n")
                       .arg(area._depot.toString(QGeoCoordinate::Degrees)));
}

void WimaServiceArea::init() {
  this->setObjectName(wimaServiceAreaName);
  connect(this, &WimaArea::pathChanged, [this] {
    if (!this->_depot.isValid() || !this->containsCoordinate(this->_depot)) {
      this->setDepot(this->center());
    }
  });
}
