#include "Background.h"
#include <Engine/GGEMain.h>

namespace gaming {
	namespace background {
		//!EXPAND
		void Background::ObtainFrom(gge::resource::FolderResource *fold) {
			Object *obj=NULL;
			Objects.Destroy();

			foreach(ResourceBase, item, fold->Subitems) {
				switch(item->getGID()) {
					case GID_IMAGE:
						if(obj==NULL) {
							obj=new Object();
							obj->item=Objects.Add(obj);
						}

						obj->Image=dynamic_cast<ImageResource*>(item);
						obj=NULL;
						break;

					case GID_DATAARRAY: 
					{
						if(obj==NULL) {
							obj=new Object();
							obj->item=Objects.Add(obj);
						}

						DataResource *dat=dynamic_cast<DataResource*>(item);
						if(!dat) continue;

						obj->Tiling=(ObjectTiling)dat->getInt(0);
						obj->Coordinates=dat->getPoint(1);
						if(dat->getCount()>2)
							obj->Size=dat->getPoint(2);
						if(dat->getCount()>3)
							obj->item->setOrder(dat->getInt(3));

						break;
					}
				}//switch type
			}//foreach item

			Refresh();
		}

		void Background::UseLayer(gge::LayerBase &layer) {
			this->layer=&layer;

			ConstructLayerStructure();

			Refresh();
		}

		void Background::ConstructLayerStructure() {
			LayerStructure.BackgroundLayer.SetRectangle(0,0, main->W,main->H);
			layer->Add(LayerStructure.BackgroundLayer, 1);
		}

		void Background::Refresh() {

			if(!layer) return;

			LayerStructure.BackgroundLayer.Clear();

			foreach(Object, object, Objects) {
				if(object->Image) {
					if(object->Tiling==Tile) {
						object->Image->DrawTiled(
							&LayerStructure.BackgroundLayer,
							object->Coordinates.x,object->Coordinates.y, 
							object->Size.Width, object->Size.Height
						);
					} else {
						object->Image->Draw(
							&LayerStructure.BackgroundLayer,
							object->Coordinates.x,object->Coordinates.y
						);
					}
				}
			}

		}
	}
}