#pragma once

#include <Widgets/Definitions.h>
#include <Widgets/Basic/Line.h>
#include "../Base.h"
#include "../File.h"
#include "../Game/Animation.h"

namespace gorgon { namespace widgets {

	class Line;

	Line *LoadLine(Base *parent, File &file, std::istream &in, int Size);

	class Line : public gge::widgets::LineResource, public Base {
		friend Line *LoadLine(gorgon::Base *parent, File &file, std::istream &in, int Size);
	public:

		virtual void Save(std::ostream &out) {
			auto start=WriteObjectStart(out, *this);


			auto propstart=WriteSectionStart(out, gge::widgets::GID::Line_Props);

			WriteLink(Mask, out);
			WriteTo(out, (int)IsLoopTiled);
			WriteTo(out, (int)Orientation);

			WriteEnd(out, propstart);

			WriteSubItems(out, *this);


			WriteEnd(out, start);
		}

		virtual GID::Type GetGID() const {
			return gge::widgets::LineResource::GetGID();
		}

		virtual void SetSources(Animation &Start, Animation &Loop, Animation &End) {

			gorgon::Base::Subitems.Clear();
			gorgon::Base::Subitems.Add(Start);
			gorgon::Base::Subitems.Add(Loop);
			gorgon::Base::Subitems.Add(End);

			gge::widgets::LineResource::SetSources(Start, Loop, End);
		}

		//templte should contain filename template which is the filename part before -
		//for instance if files are like /home/usr/border-start.png then it should be
		// /home/usr/border . This function tries to use following files from most generic
		//to least generic:
		//start, loop, end
		//cap, loop
		//loop, or none
		void ImportPNGs(const std::string &templte) {
			gorgon::Image *img;
			gorgon::Animation *start=new gorgon::Animation;
			gorgon::Animation *loop =new gorgon::Animation;
			gorgon::Animation *end  =new gorgon::Animation;
			img=importitem(templte, "-start");
			if(img) { start->Add(img); }

			img=importitem(templte, "-loop");
			if(img) { loop->Add(img); }

			img=importitem(templte, "-end");
			if(img) { end->Add(img); }

			SetSources(*start, *loop, *end);
		}

		virtual void SetMask(Line*mask) {
			gge::widgets::LineResource::SetMask(mask);
		}

		virtual void Prepare(gge::GGEMain &main, File &file) {
			Base::Prepare(main,file);

			if(!Mask)
				Mask		= dynamic_cast<LineResource*>(file.Root().FindObject(mask));
		}

		using gorgon::Base::Subitems;

	protected:
		gorgon::Image *importitem(const std::string &templte, const std::string &id) {
			if(gge::os::filesystem::IsFileExists(templte+id+".png")) {
				gorgon::Image *img=new gorgon::Image;
				img->ImportPNG(templte+id+".png");
				return img;
			}
			else {
				if(id=="-start" || id=="-end") {
					return importitem(templte, "-cap");
				}
				else if(id=="-cap") {
					return importitem(templte, "-loop");
				}
				else if(id=="-loop") {
					return importitem(templte, "");
				}
				else
					return NULL;
			}

		}
	};


}}
