#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();

		dens.SetContainer(navigation("List"));
		dens.SetHeight(navigation("List").GetUsableHeight()*6/10-newden.GetHeight()-2);
		dens.SetWidth(180);
		dens.ItemClickedEvent.Register(this,&UI::SelDen);

		newden.Text="New";
		newden.SetContainer(navigation("List"));
		newden.Move(10, dens.GetHeight());
		newden.SetWidth(80);
		newden.ClickEvent.Register(this, &UI::NewDen);

		delden.Text="Delete";
		delden.SetContainer(navigation("List"));
		delden.Move(newden.GetBounds().TopRight());
		delden.SetWidth(80);
		delden.ClickEvent.Register(this, &UI::DelDen);


		monsters.SetContainer(navigation("List"));
		monsters.SetHeight(navigation("List").GetUsableHeight()*4/10-newmonster.GetHeight()-2);
		monsters.SetWidth(180);
		monsters.SetY(newden.GetBounds().Bottom);
		monsters.ItemClickedEvent.Register(this,&UI::SelMonster);

		newmonster.Text="New";
		newmonster.SetContainer(navigation("List"));
		newmonster.Move(10, monsters.GetBounds().Bottom);
		newmonster.SetWidth(80);
		newmonster.ClickEvent.Register(this, &UI::NewMonster);

		delmonster.Text="Delete";
		delmonster.SetContainer(navigation("List"));
		delmonster.Move(newmonster.GetBounds().TopRight());
		delmonster.SetWidth(80);
		delmonster.ClickEvent.Register(this, &UI::DelMonster);



		denedit.SetContainer(toplevel);
		denedit.Move(200, 20);
		denedit.Resize(toplevel.GetUsableWidth()-200, (toplevel.GetUsableHeight()-denedit.GetY())*6/10-1);
		denedit.SetOrganizer(deneditorganizer);
		denedit.Hide();

		auto nl=deneditorganizer.nextline;

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

		deneditorganizer
			<<"Name: "<<Name<<nl
			<<"Size: "<<Size<<nl
			<<"Map: *"<<Map<<nl
			<<"HP: "<<HP<<nl
			<<"Init. Att. CD: "<<InitAttCD<<nl
			<<"Att. CD: "<<AttCD<<nl
			<<""<<nl
			<<help
			;

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

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

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

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

					CurrentDen->Add(0.f).name="HP";
					CurrentDen->Add(0.f).name="Armor";
					CurrentDen->Add(0.f).name="Init. Att. CD";
					CurrentDen->Add(0.f).name="Att. CD";

					Map.ChangeEvent();
					HP.ChangeEvent();
					Armor.ChangeEvent();
					InitAttCD.ChangeEvent();
					AttCD.ChangeEvent();
				}
			}

			changed=true;
		});
		Map.ChangeEvent.RegisterLambda([&]{
			int mw=CurrentDen->Get<resource::SizeData>(1).value.Width;
			int mh=CurrentDen->Get<resource::SizeData>(1).value.Height;
			if(CurrentDen) {
				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);
					}
					CurrentDen->Get<resource::StringData>(2+h).value=line;
				}
			}

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

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

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

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

			changed=true;
		});


		monsteredit.SetContainer(toplevel);
		monsteredit.Move(200, monsters.GetY()+5);
		monsteredit.Resize(toplevel.GetUsableWidth()-200, (toplevel.GetUsableHeight()-monsteredit.GetY())-6);
		monsteredit.SetOrganizer(monstereditorganizer);
		monsteredit.Hide();

		monstereditorganizer
			<<"Name: "<<MName<<nl
			<<"Count: "<<MCount<<nl
			<<"Init. CD: "<<MInitCD<<nl
			<<"CD: "<<MCD<<nl
			<<"Level: "<<MLevel<<nl
			<<"Max monsters: "<<MMax<<nl
		;

		MName.ChangeEvent.RegisterLambda([&]{
			if(CurrentMonster) {
				CurrentMonster->SetCaption(MName.Text);
				CurrentMonster->Get<resource::StringData>(0).value=MName.Text;
				monsters.GetItem()->Value=MName.Text;
			}

			changed=true;
		});
		MCount.ChangeEvent.RegisterLambda([&]{
			if(CurrentMonster)
				CurrentMonster->Get<resource::IntegerData>(1).value=MCount.Value;

			changed=true;
		});
		MInitCD.ChangeEvent.RegisterLambda([&]{
			if(CurrentMonster)
				CurrentMonster->Get<resource::FloatData>(2).value=MInitCD.Value;

			changed=true;
		});
		MCD.ChangeEvent.RegisterLambda([&]{
			if(CurrentMonster)
				CurrentMonster->Get<resource::FloatData>(3).value=MCD.Value;

			changed=true;
		});
		MLevel.ChangeEvent.RegisterLambda([&]{
			if(CurrentMonster)
				CurrentMonster->Get<resource::IntegerData>(4).value=MLevel.Value;

			changed=true;
		});
		MMax.ChangeEvent.RegisterLambda([&]{
			if(CurrentMonster)
				CurrentMonster->Get<resource::IntegerData>(5).value=MMax.Value;

			changed=true;
		});
	}

	~UI() {
		denedit.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() {
		denedit.Hide();
		CurrentFile.New();
		CurrentFile.Root().Add(*new gorgon::Folder("Info"));

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

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

		CurrentDen=NULL;
		dens.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:den").name="ID";

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

		ListDens();

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

	void ListDens() {
		dens.Destroy();
		for(int i=1; i<CurrentFile.Root().GetCount();i++) {
			auto &f=CurrentFile.Root().Get<gorgon::Folder>(i);
			auto &d=f.Get<gorgon::DataArray>(0);

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

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

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

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

		d.SetCaption(ss.str());
		d.Add(ss.str()).name="Name";
		d.Add(utils::Size(3,2)).name="Size";
		d.Add("000").name="Map 1";
		d.Add("010").name="Map 2";
		d.Add(1000.f).name="HP";
		d.Add(10.f).name="Armor";
		d.Add(600.f).name="Init. Att. CD";
		d.Add(240.f).name="Att. CD";

		gorgon::Folder &f=*new gorgon::Folder;
		f.Add(d);
		f.SetCaption(ss.str());

		CurrentFile.Root().Add(f);

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

		changed=true;
	}

	void SelDen() {
		if(dens.GetSelectedItem()) {
			denedit.Show();
			CurrentDenFold=&CurrentFile.Root().Get<gorgon::Folder>(dens.FindLocation(dens.GetSelectedItem())+1);
			CurrentDen=&CurrentDenFold->Get<gorgon::DataArray>(0);
			Name.Text=CurrentDen->getString(0);
			int mh=CurrentDen->Get<resource::SizeData>(1).value.Height;
			std::string s="";
			for(int h=0;h<mh;h++)
				s+=CurrentDen->getString(2+h)+",";
			Map.Text=s;
			Size.Value=CurrentDen->getSize(1);
			HP.Value=CurrentDen->getFloat(2+mh);
			Armor.Value=CurrentDen->getFloat(3+mh);
			InitAttCD.Value=CurrentDen->getFloat(4+mh);
			AttCD.Value=CurrentDen->getFloat(5+mh);

			ListMonsters();
		}
		else {
			CurrentDen=NULL;
			denedit.Hide();
		}
	}

	void DelDen() {
		if(CurrentDenFold)
			CurrentFile.Root().Remove(CurrentDenFold);

		ListDens();

		changed=true;
	}

	void ListMonsters() {
		monsters.Destroy();
		monsteredit.Hide();

		if(!CurrentDenFold) return;

		for(int i=1; i<CurrentDenFold->GetCount();i++) {
			auto &d=CurrentDenFold->Get<gorgon::DataArray>(i);

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

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

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

		std::stringstream ss;
		ss<<"Monster "<<CurrentDenFold->GetCount();

		d.SetCaption(ss.str());
		d.Add(ss.str()).name="Name";
		d.Add(1).name="Spawn count";
		d.Add(120.f).name="Init. CD";
		d.Add(60.f).name="CD";
		d.Add(1).name="Level";
		d.Add(5).name="Max monsters";

		CurrentDenFold->Add(d);

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

		changed=true;
	}

	void SelMonster() {
		if(monsters.GetSelectedItem()) {
			monsteredit.Show();
			CurrentMonster=&CurrentDenFold->Get<gorgon::DataArray>(monsters.FindLocation(monsters.GetSelectedItem())+1);

			MName.Text=CurrentMonster->getString(0);
			MCount.Value=CurrentMonster->getInt(1);
			MInitCD.Value=CurrentMonster->getFloat(2);
			MCD.Value=CurrentMonster->getFloat(3);
			MLevel.Value=CurrentMonster->getInt(4);
			MMax.Value=CurrentMonster->getInt(5);
		}
		else {
			CurrentMonster=NULL;
			monsteredit.Hide();
		}
	}

	void DelMonster() {
		if(CurrentMonster)
			CurrentDenFold->Remove(CurrentMonster);

		ListMonsters();

		changed=true;
	}

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

	widgets::Listbox<> dens;
	widgets::Button newden;
	widgets::Button delden;

	widgets::InlinePanel denedit;

	widgets::Listbox<> monsters;
	widgets::Button newmonster;
	widgets::Button delmonster;

	widgets::InlinePanel monsteredit;

	widgets::Textbox Name;
	widgets::Numberbox<utils::Point> Size;
	widgets::Textbox Map;
	widgets::Numberbox<float> HP, Armor;
	widgets::Numberbox<float> InitAttCD, AttCD;
	widgets::Label help;

	widgets::Textbox MName;
	widgets::Numberbox<int> MCount;
	widgets::Numberbox<float> MInitCD, MCD;
	widgets::Numberbox<int> MLevel, MMax;


	widgets::LinearOrganizer deneditorganizer;
	widgets::LinearOrganizer monstereditorganizer;

	gorgon::File CurrentFile;
	gorgon::DataArray *CurrentDen;
	gorgon::Folder *CurrentDenFold;
	gorgon::DataArray *CurrentMonster;

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