#pragma once

#include <Widgets/Panel.h>
#include <Widgets/Label.h>
#include "../Mechanics/PlayerGame.h"
#include <sstream>
#include <Widgets/Organizers/LinearOrganizer.h>
#include "../Mechanics/Townsfolk.h"
#include "../Mechanics/Soldier.h"
#include <Widgets/Window.h>
#include <Widgets/DialogWindow.h>
#include <Widgets/Listbox.h>
#include "../Assets/Buildings.h"
#include "Actions.h"
#include <Resource/Folder.h>
#include <Resource/File.h>
#include <Resource/DataArray.h>
#include <Widgets/Dialogs/Message.h>

//for vs
#undef interface

namespace interface {

	class MapSelection : public gge::widgets::DialogWindow {
	public:
		MapSelection() : accepted("Accepted", this) {
			SetOrganizer(organizer);

			ok.Text="Ok";
			cancel.Text="Cancel";

			SetDefault(ok);
			SetCancel(cancel);

			Title="Map selection";

			list.SetHeight(120);
			Resize(300, 300);

			title.SetBlueprint(gge::widgets::WR.Labels.Bold);

			organizer.AutosizeWindows=false;

			auto nl=organizer.nextline;

			organizer
				<<list<<nl
				<<title<<nl
				<<"*Author:*"<<author<<nl
				<<info<<nl
			;
			//RemoveOrganizer();

			AddDialogButton(cancel);
			AddDialogButton(ok);

			Hide();

			cancel.ClickEvent.Register(this, &gge::widgets::DialogWindow::Close);
			ok.Disable();

			list.ItemClickedEvent.RegisterLambda([&] {
				if(this->list.GetSelectedItem()) {
					ok.Enable();

					try {
						gge::resource::File file;
						file.AddGameLoaders();
						file.LoadFirst("Maps/"+this->list.GetValue()+"/map.gor");

						auto &data=file.Root().Get<gge::resource::Folder>(0).Get<gge::resource::DataArray>(0);

						title.Text=data.getString(1);
						
						author.Text=data.getString(2);
						info.Text=data.getString(4);

						organizer.Reorganize();
					}
					catch(...) {
						gge::widgets::dialog::ShowMessage("Cannot load "+this->list.GetValue()+" to display info.", "Load map");
					}
				}
			});

			ok.ClickEvent.RegisterLambda([&]{
				accepted(list.GetValue());
				Close();
			});
		}

		virtual void Show() {
			list.DeleteAll();

			gge::os::filesystem::DirectoryIterator it("Maps");

			for(;it.IsValid();it.Next()) {
				if(it->length() && (*it)[0]!='.') {
					list.Add(*it);
				}
			}

			gge::widgets::DialogWindow::Show(true);
			/*
			Move(
				50,
				gge::widgets::TopLevel.GetHeight()-GetHeight()-35
			);
			*/
			MoveToCenter();

			ok.Disable();
		}



		gge::utils::EventChain<MapSelection, std::string> accepted;
	protected:
		gge::widgets::Listbox<std::string> list;
		gge::widgets::Button ok, cancel;
		gge::widgets::Label title, author, info;
		gge::widgets::LinearOrganizer organizer;

	};

}
