// fgmrank.cc

#include "fgmrank.h"

#ifndef __SGI_STL_VECTOR_H
#include <vector>
#endif

struct FGMatchRanking::Internal_FGMatchRanking {
  bool mIsMatch;
  std::vector<int> mValues;
};

FGMatchRanking::FGMatchRanking()
{
  mpInternals = new Internal_FGMatchRanking;
  mpInternals->mIsMatch = false;
}

FGMatchRanking::~FGMatchRanking()
{
  delete mpInternals;
}

FGMatchRanking::FGMatchRanking(const FGMatchRanking& other)
{
  mpInternals = new Internal_FGMatchRanking;
  *mpInternals = *other.mpInternals;
}

FGMatchRanking&
FGMatchRanking::operator=(const FGMatchRanking& other)
{
  if (this == &other) {
    return *this;
  }

  // Free existing stuff
  delete mpInternals;

  mpInternals = new Internal_FGMatchRanking;
  *mpInternals = *other.mpInternals;

  return *this;
}

void
FGMatchRanking::AddValue(int value)
{
  mpInternals->mValues.push_back(value);
}

void
FGMatchRanking::SetMatch(void)
{
  mpInternals->mIsMatch = true;
}

bool
FGMatchRanking::IsMatch(void) const
{
  return mpInternals->mIsMatch;
}

bool
FGMatchRanking::operator<(const FGMatchRanking& other) const
{
  // Always less than if we're not a match
  // n.b. nothing should be comparing against non-match anyway
  if (mpInternals->mIsMatch == false) {
    return true;
  }

  // Never less than, if comparing against non-match
  if (other.mpInternals->mIsMatch == false) {
    return false;
  }

  // Otherwise iterate through components one by one
  int thisSize = mpInternals->mValues.size();
  int otherSize = other.mpInternals->mValues.size();
  int min = thisSize;
  if (otherSize < min) {
    min = otherSize;
  }

  int index;
  for (index = 0; index < min; index++) {
    if (mpInternals->mValues[index] < other.mpInternals->mValues[index]) {
      // Yes we are an older version
      return true;
    } else if (mpInternals->mValues[index] > other.mpInternals->mValues[index]) {
      // Newer version.. so not older version
      return false;
    }
    // else.. equal so progress to next component and compare
  }

  // Oh we ran out of comparisions
  // If we have more bits of version we are greater (not less than)
  if (thisSize > otherSize) {
    return false;
  }

  // Oh we are equal
  // That's not less than
  return false;
}
