#include "WimaServiceArea.h"

const char *WimaServiceArea::wimaServiceAreaName = "Service Area";
const char *WimaServiceArea::depotLatitudeName = "DepotLatitude";
const char *WimaServiceArea::depotLongitudeName = "DepotLongitude";
const char *WimaServiceArea::depotAltitudeName = "DepotAltitude";

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

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

/*!
 * \overload operator=()
 *
 * Calls the inherited operator WimaArea::operator=().
 */
WimaServiceArea &WimaServiceArea::operator=(const WimaServiceArea &other) {
  WimaArea::operator=(other);
  this->setDepot(other.depot());
  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;
  json[depotLatitudeName] = _depot.latitude();
  json[depotLongitudeName] = _depot.longitude();
  json[depotAltitudeName] = _depot.altitude();
}

bool WimaServiceArea::loadFromJson(const QJsonObject &json,
                                   QString &errorString) {
  bool retVal = false;
  if (this->WimaArea::loadFromJson(json, errorString)) {
    double lat = 0;
    if (json.contains(depotLatitudeName) &&
        json[depotLatitudeName].isDouble()) {
      lat = json[depotLatitudeName].toDouble();
      double lon = 0;
      if (json.contains(depotLongitudeName) &&
          json[depotLongitudeName].isDouble()) {
        lon = json[depotLongitudeName].toDouble();
        double alt = 0;
        if (json.contains(depotAltitudeName) &&
            json[depotAltitudeName].isDouble()) {
          alt = json[depotAltitudeName].toDouble();
          this->setDepot(QGeoCoordinate(lat, lon, alt));
          retVal = true;
        } else {
          errorString = "Not able to load depot altitude.";
        }
      } else {
        errorString = "Not able to load depot longitude.";
      }
    } else {
      errorString = "Not able to load depot latitude.";
    }
    retVal = true;
  }
  return retVal;
}

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());
    }
  });
}
