// Abstract strength indicator bar
class StrengthBar : ScriptedGuiHandler {
	Color outlineCol;
	Color[] colors;
	float[] sizes;
	uint us;
	float sum;
	bool visible;

	bool hasUs;
	bool hasOther;
	uint hasAmount;

	GuiElement@ element;

	StrengthBar() {
		outlineCol = Color(64, 255, 255, 255);
	}

	void init(GuiElement@ ele) {
		@element = ele;
	}

	void update(System@ sys, SystemStats& stats) {
		if (element.isVisible()) {
			uint cnt = getEmpireCount();
			hasUs = false;
			hasOther = false;
			hasAmount = 0;

			// Resize if necessary
			if (sizes.length() != cnt)
				sizes.resize(cnt);
			if (colors.length() != cnt)
				colors.resize(cnt);

			// Section where system is locked
			sum = 0.f;
			Empire@ us = getActiveEmpire();
			{
				stats.prepare(sys);
				visible = stats.visible;

				if (!visible) {
					stats.prepare(null);
					return;
				}

				for (uint i = 0; i < cnt; ++i) {
					const Empire@ emp = getEmpire(i);

					if (emp.isValid()) {
						colors[i] = emp.color;
						sizes[i] = stats.getStat(emp, "str");
						sum += sizes[i];
					}
					else {
						sizes[i] = 0.f;
					}

					if (emp.ID == us.ID) {
						this.us = i;
						
						if (sizes[i] > 0.01f) {
							hasUs = true;
							++hasAmount;
						}
					}
					else {
						if (sizes[i] > 0.01f) {
							hasOther = true;
							++hasAmount;
						}
					}
				}

				stats.prepare(null);
			}

			// Normalize sizes to 1.f
			if (sum > 0.01f) {
				for (uint i = 0; i < cnt; ++i) {
					sizes[i] /= sum;
				}
			}
		}
	}

	void draw(GuiElement@ ele) {
		if (sum > 0.01f && visible) {
			recti absPos = ele.getAbsolutePosition();
			const float width = absPos.getWidth();
			const float height = absPos.getHeight();
			const pos2di topLeft = absPos.UpperLeftCorner;

			float progression = width;
			uint cnt = min(sizes.length(), colors.length());

			for (uint i = 0; i < cnt; ++i) {
				if (i == us) {
					// Draw our bar from the left so it's the first
					drawRect(recti(topLeft, dim2di(ceil(sizes[i]*width), height)), colors[i]);
				}
				else {
					// Draw other bars from the right
					float sz = ceil(sizes[i]*width);
					progression -= sz;

					drawRect(recti(pos2di(topLeft.x+progression, topLeft.y), dim2di(sz, height)), colors[i]);
				}
			}

			drawRectOutline(absPos, outlineCol);
		}
	}

	EventReturn onKeyEvent(GuiElement@,const KeyEvent&) {
		return ER_Pass;
	}
	
	EventReturn onMouseEvent(GuiElement@,const MouseEvent&) {
		return ER_Pass;
	}
	
	EventReturn onGUIEvent(GuiElement@ ele, const GUIEvent& event) {
		return ER_Pass;
	}
};
