#pragma once

#include <vector>
#include <string>
#include <Widgets/Main.h>
#include <Widgets/FullscreenPanel.h>
#include <Widgets/Tabpanel.h>
#include <Widgets/Listbox.h>
#include "../Common/FileHandling.h"
#include <iosfwd>
#include <Widgets/Dialogs/TextInput.h>
#include <Gorgon/Folder.h>
#include <Gorgon/Base.h>
#include <Gorgon/Game/Animation.h>
#include <Gorgon/Generic/DataArray.h>
#include <Widgets/Dialogs/Query.h>
#include <Widgets/Numberbox.h>
#include <Gorgon/Extended/Sound.h>
#include <Gorgon/Link.h>
#include <Widgets/InlinePanel.h>
#include <Widgets/Dialogs/Message.h>


class UI {
public:

	UI() {
		changed=false;

		CurrentFile.AddGameLoaders();
		CurrentFile.SetFileType(gorgon::GID::File::Game);

		os::window::Closing.RegisterLambda([&](bool &reply){
			if(changed) {
				AskQuit();
				reply=false;
			}
		});

		toplevel.Padding=0;


		navigation.SetContainer(toplevel);
		navigation.FillContainer();
		navigation.SetWidth(200);
		navigation.Add("Files");
		navigation.Add("List");
		navigation("List").Disable();
		navigation.reorganize();


		file.SetPanel(navigation("Files"));
		file.SetPanel(navigation("Files"));
		file.Quit.ClickEvent.RegisterLambda([&]{
			if(changed) AskQuit();
			else        Main.Exit(0);
		});
		file.New.ClickEvent.Register(this, &UI::NewFile);
		file.Load.ClickEvent.Register(this, &UI::LoadFile);
		file.Save.ClickEvent.RegisterLambda([&]{ actionafter=action_none; Save(); });
		file.SaveAs.ClickEvent.RegisterLambda([&]{ actionafter=action_none; AskSavename(); });
		file.RefreshFiles();

		townbuildings.SetContainer(navigation("List"));
		townbuildings.SetHeight(navigation("List").GetUsableHeight()-newtownbuilding.GetHeight()-2);
		townbuildings.SetWidth(180);
		townbuildings.ItemClickedEvent.Register(this,&UI::SelTownBuilding);

		newtownbuilding.Text="New";
		newtownbuilding.SetContainer(navigation("List"));
		newtownbuilding.Move(10, townbuildings.GetHeight());
		newtownbuilding.SetWidth(80);
		newtownbuilding.ClickEvent.Register(this, &UI::NewTownBuilding);

		deltownbuilding.Text="Delete";
		deltownbuilding.SetContainer(navigation("List"));
		deltownbuilding.Move(newtownbuilding.GetBounds().TopRight());
		deltownbuilding.SetWidth(80);
		deltownbuilding.ClickEvent.Register(this, &UI::DelTownBuilding);

		townbuildingedit.SetContainer(toplevel);
		townbuildingedit.Move(200, 20);
		townbuildingedit.Resize(toplevel.GetUsableWidth()-200, toplevel.GetUsableHeight()-townbuildingedit.GetY()-1);
		townbuildingedit.SetOrganizer(townbuildingeditorganizer);
		townbuildingedit.Hide();

		auto nl=townbuildingeditorganizer.nextline;

		help.Text="For map, 0 non passable, you may use , to separate rows.";

		townbuildingeditorganizer
			<<"Name: "<<Name<<nl
			<<"Size: "<<Size<<nl
			<<"Map: *"<<Map<<nl
			<<"HP: "<<HP<<nl
			<<"Odds: "<<Odds<<nl
			<<"Spacing: "<<Spacing<<nl
			<<""<<nl
			<<help
		;

		Name.ChangeEvent.RegisterLambda([&]{
			if(CurrentTownBuilding) {
				CurrentTownBuilding->SetCaption(Name.Text);
				CurrentTownBuilding->Get<resource::StringData>(0).value=Name.Text;
				townbuildings.GetItem()->Value=Name.Text;

				changed=true;
			}
		});
		Size.ChangeEvent.RegisterLambda([&]{
			int mh=CurrentTownBuilding->Get<resource::SizeData>(1).value.Height;
			if(CurrentTownBuilding) {
				CurrentTownBuilding->Get<resource::SizeData>(1).value=(utils::Point)Size.Value;
				int ch=CurrentTownBuilding->Get<resource::SizeData>(1).value.Height;

				if(mh>ch) {
					for(int i=0;i<mh-ch;i++)
						CurrentTownBuilding->Delete(2);
				}
				else if(mh<ch) {
					//as data array does not support reordering, we remove the rest and add again
					for(int i=0;CurrentTownBuilding->GetCount()>2;i++)
						CurrentTownBuilding->Delete(2);

					for(int i=0;i<ch;i++) {
						std::stringstream ss;
						ss<<"Map "<<i+1;
						CurrentTownBuilding->Add("").name=ss.str();
					}

					CurrentTownBuilding->Add(0.f).name="HP";
					CurrentTownBuilding->Add(0.f).name="Armor";
					CurrentTownBuilding->Add(0.f).name="Odds";
					CurrentTownBuilding->Add(0).name="Spacing";

					Map.ChangeEvent();
					HP.ChangeEvent();
					Armor.ChangeEvent();
					Odds.ChangeEvent();
					Spacing.ChangeEvent();
				}
			}

			changed=true;
		});
		Map.ChangeEvent.RegisterLambda([&]{
			int mw=CurrentTownBuilding->Get<resource::SizeData>(1).value.Width;
			int mh=CurrentTownBuilding->Get<resource::SizeData>(1).value.Height;
			if(CurrentTownBuilding) {
				unsigned ind=0;
				std::string s=Map.Text;
				s.erase(std::remove(s.begin(), s.end(), '|'), s.end());
				s.erase(std::remove(s.begin(), s.end(), ','), s.end());
				s.erase(std::remove(s.begin(), s.end(), ' '), s.end());
				for(int h=0;h<mh;h++) {
					std::string line="";
					for(int w=0;w<mw;w++) {
						char t='1';
						if(ind<s.length()) {
							t=s[ind++];
						}
						line.append(1, t);
					}
					CurrentTownBuilding->Get<resource::StringData>(2+h).value=line;
				}
			}

			changed=true;
		});
		HP.ChangeEvent.RegisterLambda([&]{
			int mh=CurrentTownBuilding->Get<resource::SizeData>(1).value.Height;
			if(CurrentTownBuilding)
				CurrentTownBuilding->Get<resource::FloatData>(2+mh).value=HP.Value;

			changed=true;
		});
		
		Armor.ChangeEvent.RegisterLambda([&]{
			int mh=CurrentTownBuilding->Get<resource::SizeData>(1).value.Height;
			if(CurrentTownBuilding)
				CurrentTownBuilding->Get<resource::FloatData>(3+mh).value=Armor.Value;

			changed=true;
		});
		Odds.ChangeEvent.RegisterLambda([&]{
			int mh=CurrentTownBuilding->Get<resource::SizeData>(1).value.Height;
			if(CurrentTownBuilding)
				CurrentTownBuilding->Get<resource::FloatData>(4+mh).value=Odds.Value;

			changed=true;
		});
		Spacing.ChangeEvent.RegisterLambda([&]{
			int mh=CurrentTownBuilding->Get<resource::SizeData>(1).value.Height;
			if(CurrentTownBuilding)
				CurrentTownBuilding->Get<resource::IntegerData>(5+mh).value=Spacing.Value;

			changed=true;
		});
	}

	~UI() {
		townbuildingedit.RemoveOrganizer();
	}


	void SetDirectory(const std::string &dir) {
		file.SetDirectory(dir);
	}

	void AskQuit() {
		auto &d=widgets::dialog::AskConfirm("You have changed the file, do you wish to save?", "Quit");
		d.RepliedEvent.RegisterLambda([&](bool reply){
			if(reply) {
				actionafter=action_quit;
				Save();
				return;
			}
			else {
				Main.Exit(0);
			}
		});
		d.ShowCancel=true;
	}

	void AskSavename() {
		widgets::dialog::AskText("Enter the name for the file.", CurrentFile.GetFilename(), 
			"Save").RepliedEvent.RegisterLambda([&](const std::string &str) {
				CurrentFile.SetFilename(file.directory.Text+"/"+str);
				Save();
		});
	}

	bool Save() {
		if(CurrentFile.GetFilename()=="") {
			AskSavename();
			return false;
		}

		try {
			CurrentFile.SaveFile(CurrentFile.GetFilename());
			file.RefreshFiles();
		}
		catch(std::exception ex) {
			widgets::dialog::ShowMessage(std::string(ex.what())+"\nCheck if file path is valid.", "Save error");
		}
		changed=false;

		if(actionafter==action_newfile) {
			NewFile();
		}
		else if(actionafter==action_loadfile) {
			LoadFile();
		}
		else if(actionafter==action_quit) {
			Main.Exit(0);
		}

		return true;
	}

	void AskNew() {
		auto &d=widgets::dialog::AskConfirm("You have changed the file, do you wish to save?", "New file");
		d.RepliedEvent.RegisterLambda([&](bool reply){
			if(reply) {
				actionafter=action_newfile;
				Save();
				return;
			}
			else {
				ForceNewFile();
			}
		});
		d.ShowCancel=true;
	}

	void NewFile() {
		if(changed) {
			AskNew();
		}
		else {
			ForceNewFile();
		}
	}

	void ForceNewFile() {
		townbuildingedit.Hide();
		CurrentFile.New();
		CurrentFile.Root().Add(*new gorgon::Folder("Info"));

		gorgon::DataArray &dinf=*new gorgon::DataArray;
		dinf.SetCaption("Info");
		dinf.Add("trinlibr:townbld").name="ID";

		CurrentFile.Root().Get<gorgon::Folder>(0).Add(dinf);

		CurrentTownBuilding=NULL;
		townbuildings.Destroy();
		navigation("List").Enable();
		file.Save.Enable();
		file.SaveAs.Enable();
		navigation.reorganize();
		navigation.Activate(navigation("List"));
	}

	void AskLoad() {
		auto &d=widgets::dialog::AskConfirm("You have changed the file, do you wish to save?", "Load file");
		d.RepliedEvent.RegisterLambda([&](bool reply){
			if(reply) {
				actionafter=action_loadfile;
				Save();
				return;
			}
			else {
				ForceLoadFile();
			}
		});
		d.ShowCancel=true;
	}

	void LoadFile() {
		if(changed) {
			AskLoad();
		}
		else
			ForceLoadFile();

	}

	void ForceLoadFile() {
		std::string filename=(std::string)file.directory.Text + "/" + file.lst.GetValue().Filename;

		CurrentFile.LoadFile(filename);
		CurrentFile.Prepare();

		if(CurrentFile.Root().Get<gorgon::Folder>(0).GetCount()==0) {
			gorgon::DataArray &dinf=*new gorgon::DataArray;
			dinf.SetCaption("Info");
			dinf.Add("trinlibr:townbld").name="ID";

			CurrentFile.Root().Get<gorgon::Folder>(0).Add(dinf);
		}

		ListTownBuildings();

		navigation("List").Enable();
		file.Save.Enable();
		file.SaveAs.Enable();
		navigation.reorganize();
		navigation.Activate(navigation("List"));
	}

	void ListTownBuildings() {
		townbuildings.Destroy();
		for(int i=1; i<CurrentFile.Root().GetCount();i++) {
			auto &d=CurrentFile.Root().Get<gorgon::DataArray>(i);

			townbuildings.Add(d.getString(0));
		}

		if(townbuildings.GetCount())
			townbuildings[0].Accessed();
	}

	void NewTownBuilding() {
		gorgon::DataArray &d=*new gorgon::DataArray;

		std::stringstream ss;
		ss<<"TownBuilding "<<CurrentFile.Root().GetCount();

		d.SetCaption(ss.str());
		d.Add(ss.str()).name="Name";
		d.Add(utils::Size(2,2)).name="Size";
		d.Add("11").name="Map 1";
		d.Add("10").name="Map 2";
		d.Add(1000.f).name="HP";
		d.Add(10.f).name="Armor";
		d.Add(10.f).name="Odds";
		d.Add(0).name="Spacing";

		CurrentFile.Root().Add(d);

		townbuildings.Add(ss.str());
		townbuildings.GetItem(townbuildings.GetCount()-1)->Accessed();

		changed=true;
	}

	void SelTownBuilding() {
		if(townbuildings.GetSelectedItem()) {
			townbuildingedit.Show();
			CurrentTownBuilding=&CurrentFile.Root().Get<gorgon::DataArray>(townbuildings.FindLocation(townbuildings.GetSelectedItem())+1);
			Name.Text=CurrentTownBuilding->getString(0);
			int mh=CurrentTownBuilding->Get<resource::SizeData>(1).value.Height;
			std::string s="";
			for(int h=0;h<mh;h++)
				s+=CurrentTownBuilding->getString(2+h)+",";
			Map.Text=s;
			Size.Value=CurrentTownBuilding->getSize(1);
			HP.Value=CurrentTownBuilding->getFloat(2+mh);
			Armor.Value=CurrentTownBuilding->getFloat(3+mh);
			Odds.Value=CurrentTownBuilding->getFloat(4+mh);
			Spacing.Value=CurrentTownBuilding->getInt(5+mh);
		}
		else {
			CurrentTownBuilding=NULL;
			townbuildingedit.Hide();
		}
	}

	void DelTownBuilding() {
		if(CurrentTownBuilding)
			CurrentFile.Root().Remove(CurrentTownBuilding);

		ListTownBuildings();

		changed=true;
	}

	widgets::FullscreenPanel toplevel;
	widgets::Tabpanel navigation;
	FileHandler file;

	widgets::Listbox<> townbuildings;
	widgets::Button newtownbuilding;
	widgets::Button deltownbuilding;

	widgets::InlinePanel townbuildingedit;

	widgets::Textbox Name;
	widgets::Numberbox<utils::Point> Size;
	widgets::Textbox Map;
	widgets::Numberbox<float> HP, Armor, Odds;
	widgets::Numberbox<int> Spacing;
	widgets::Label help;

	widgets::LinearOrganizer townbuildingeditorganizer;

	gorgon::File CurrentFile;
	gorgon::DataArray *CurrentTownBuilding;

	bool changed;
	enum {
		action_none,
		action_newfile,
		action_loadfile,
		action_quit
	} actionafter;
};
