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

		gens.SetContainer(navigation("List"));
		gens.SetHeight(navigation("List").GetUsableHeight()-newgen.GetHeight()-2);
		gens.SetWidth(180);
		gens.ItemClickedEvent.Register(this,&UI::SelGen);

		newgen.Text="New";
		newgen.SetContainer(navigation("List"));
		newgen.Move(10, gens.GetHeight());
		newgen.SetWidth(80);
		newgen.ClickEvent.Register(this, &UI::NewGen);

		delgen.Text="Delete";
		delgen.SetContainer(navigation("List"));
		delgen.Move(newgen.GetBounds().TopRight());
		delgen.SetWidth(80);
		delgen.ClickEvent.Register(this, &UI::DelGen);

		genedit.SetContainer(toplevel);
		genedit.Move(200, 40);
		genedit.Resize(toplevel.GetUsableWidth()-200, toplevel.GetUsableHeight()-genedit.GetY()-1);
		genedit.SetOrganizer(geneditorganizer);
		genedit.Hide();

		geneditorganizer
			<<"Name: "<<Name<<geneditorganizer.nextline
			<<"Odds: "<<Odds<<geneditorganizer.nextline
			<<"Total stats: "<<Total<<geneditorganizer.nextline
			<<"Stat range: "<<Range<<geneditorganizer.nextline
		;

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

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

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

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

			changed=true;
		});
	}

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

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

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

		CurrentGen=NULL;
		gens.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:townsfolk").name="ID";

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

		ListGens();

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

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

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

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

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

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

		d.SetCaption(ss.str());
		d.Add(ss.str()).name="Name";
		d.Add(1.0f).name="Odds";
		d.Add(90.0f).name="Total stats";
		d.Add(20.0f).name="Stat Range";

		CurrentFile.Root().Add(d);

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

		changed=true;
	}

	void SelGen() {
		if(gens.GetSelectedItem()) {
			genedit.Show();
			CurrentGen=&CurrentFile.Root().Get<gorgon::DataArray>(gens.FindLocation(gens.GetSelectedItem())+1);
			Name.Text=CurrentGen->getString(0);
			Odds.Value=CurrentGen->getFloat(1);
			Total.Value=CurrentGen->getFloat(2);
			Range.Value=CurrentGen->getFloat(3);
		}
		else {
			CurrentGen=NULL;
			genedit.Hide();
		}
	}

	void DelGen() {
		if(CurrentGen)
			CurrentFile.Root().Remove(CurrentGen);

		ListGens();

		changed=true;
	}

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

	widgets::Listbox<> gens;
	widgets::Button newgen;
	widgets::Button delgen;

	widgets::InlinePanel genedit;
	widgets::Textbox Name;
	widgets::Numberbox<float> Odds, Total, Range;
	widgets::LinearOrganizer geneditorganizer;

	gorgon::File CurrentFile;
	gorgon::DataArray *CurrentGen;

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