#include "PieSector.hpp"
#include "glew.h"

PieSector::PieSector(DataGroup* pDataGroup, float fBeginValue, float fValueScaleFactor, int iMoveSlice) {
  iType = PIE_SECTOR;
  this->pDataGroup = pDataGroup;

  std::vector<DataEntry*> vDataEntries = pDataGroup->GetDataEntries();
  
  //pie slices
  float fAccumulatedValues = fBeginValue;

  for (unsigned int i = 0; i < vDataEntries.size(); i++) {
    vSlices.push_back(new PieSlice(vDataEntries.at(i), fAccumulatedValues, fValueScaleFactor));
    fAccumulatedValues += (float) vDataEntries.at(i)->GetValue();
  }

  //label
  float fLabelValue = fAccumulatedValues * fValueScaleFactor - (fAccumulatedValues - fBeginValue) * fValueScaleFactor / 2.0f;

  float fXCoordinate = sin(fLabelValue / 100.0f * 2.0f * PI) /
    ((float) -WIDTH / (float) HEIGHT) * PIE_CHART_LABEL_RADIUS + PIE_CHART_CENTER_X;
  fXCoordinate = (fXCoordinate + 1.0f) / 2.0f * WIDTH;

  float fYCoordinate = cos(fLabelValue / 100.0f * 2.0f * PI) *
    PIE_CHART_LABEL_RADIUS + PIE_CHART_CENTER_Y;
  fYCoordinate = (1.0f - fYCoordinate) / 2.0f * HEIGHT + iMoveSlice * PIE_CHART_LABEL_OFFSET;

  int iAlignment;

  if ((fLabelValue <= 3.0f) || ((fLabelValue >= 47.0f) && (fLabelValue <= 53.0f)) || (fLabelValue >= 97.0f)) {
     iAlignment = Qt::AlignCenter;
  }
  else if (fLabelValue > 53.0f) {
    iAlignment = Qt::AlignLeft;
  }
  else {
    iAlignment = Qt::AlignRight;
  }

  pLabel = new Label(QObject::tr(pDataGroup->GetName().c_str()), FONTSTYLE_BAR,
    fXCoordinate, fYCoordinate, ORIENTATION_HORIZONTAL, iAlignment);
}

PieSector::~PieSector() {
  while (vSlices.size() > 0) {
    std::vector<PieSlice*>::iterator it = vSlices.begin();

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

  delete pLabel;
}

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

void PieSector::DrawLabels(QPainter* pPainter) {
  pLabel->Draw(pPainter);
}

void PieSector::ChangePosition(float fDeltaLeft, float fDeltaTop, float fDeltaBottom) {
  UNREFERENCED(fDeltaLeft);
  UNREFERENCED(fDeltaTop);
  UNREFERENCED(fDeltaBottom);
}

void PieSector::Scale(float fDeltaWidth, float fDeltaHeight) {
  UNREFERENCED(fDeltaWidth);
  UNREFERENCED(fDeltaHeight);
}

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

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

std::vector<PieSlice*> PieSector::GetSlices() {
  return vSlices;
}