#include "StackedBar.hpp"

StackedBar::StackedBar(DataGroup* pDataGroup, float fLeft, float fWidth, double dHighestGridValue) {
  iType = STACKED_BAR;
  this->pDataGroup = pDataGroup;
  this->fLeft = fLeft;
  this->fWidth = fWidth;

  std::vector<DataEntry*> vDataEntries = pDataGroup->GetDataEntries();
  
  //label
  pLabel = new Label(QObject::tr(pDataGroup->GetName().c_str()), FONTSTYLE_BAR,
    (fLeft + fWidth / 2.0f + 1.0f) / 2.0f * WIDTH,
    (1.0f - (ORIGIN_Y + 1.0f) / 2.0f) * HEIGHT + BAR_TEXT_OFFSET, ORIENTATION_HORIZONTAL, Qt::AlignCenter);
  
  //bars
  float fBottomSummed = 0.0f;

  for (unsigned int i = 0; i < vDataEntries.size(); i++) {
    float fHeight = vDataEntries.at(i)->GetValue() / dHighestGridValue * (UPPER_Y - ORIGIN_Y);
    float fTop = fHeight + fBottomSummed + ORIGIN_Y;

    vBars.push_back(new Bar(vDataEntries.at(i), fLeft, fTop, fBottomSummed + ORIGIN_Y, fWidth, pLabel));
    fBottomSummed += fabs(fHeight);
  }
}

StackedBar::~StackedBar() {
  while (vBars.size() > 0) {
    std::vector<Bar*>::iterator it = vBars.begin();

    if (it != vBars.end()) {
      delete *it;
      vBars.erase(it);
    }
  }

  delete pLabel;
}

void StackedBar::Draw(QPainter* pPainter) {
  for (unsigned int i = 0; i < vBars.size(); i++) {
    vBars.at(i)->Draw(pPainter);
  }
}

void StackedBar::DrawLabels(QPainter* pPainter) {
  vBars.at(0)->DrawLabels(pPainter);
}

void StackedBar::ChangePosition(float fDeltaLeft, float fDeltaTop, float fDeltaBottom) {
  UNREFERENCED(fDeltaTop);
  UNREFERENCED(fDeltaBottom);
  fLeft += fDeltaLeft;

  pLabel->ChangePosition((fLeft + fWidth / 2.0f + 1.0f) / 2.0f * WIDTH,
    (1.0f - (ORIGIN_Y + 1.0f) / 2.0f) * HEIGHT + BAR_TEXT_OFFSET);
}

void StackedBar::Scale(float fDeltaWidth, float fDeltaHeight) {
  UNREFERENCED(fDeltaHeight);
  fWidth += fDeltaWidth;
}

void StackedBar::ChangeAlpha(float fDeltaAlpha) {
  UNREFERENCED(fDeltaAlpha);
}

DataGroup* StackedBar::GetDataGroup() {
  return pDataGroup;
}

std::vector<Bar*> StackedBar::GetBars() {
  return vBars;
}