#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>
#include <Utils/StringEnum.h>
#include <Widgets/Combobox.h>

class UI {
public:

#define eventhandler(name, ind) name.ChangeEvent.RegisterLambda([&]{ if(CurrentArtisan) CurrentArtisan->Get<resource::FloatData>(ind).value = name.Value; });

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

		artisans.SetContainer(navigation("List"));
		artisans.SetHeight(navigation("List").GetUsableHeight()-newartisan.GetHeight()-2);
		artisans.SetWidth(180);
		artisans.ItemClickedEvent.Register(this,&UI::SelArtisan);

		newartisan.Text="New";
		newartisan.SetContainer(navigation("List"));
		newartisan.Move(10, artisans.GetHeight());
		newartisan.SetWidth(80);
		newartisan.ClickEvent.Register(this, &UI::NewArtisan);

		delartisan.Text="Delete";
		delartisan.SetContainer(navigation("List"));
		delartisan.Move(newartisan.GetBounds().TopRight());
		delartisan.SetWidth(80);
		delartisan.ClickEvent.Register(this, &UI::DelArtisan);

		artisanedit.SetContainer(toplevel);
		artisanedit.Move(200, 30);
		artisanedit.Resize(toplevel.GetUsableWidth()-200, toplevel.GetUsableHeight()-artisanedit.GetY()-1);
		artisanedit.SetOrganizer(artisaneditorganizer);
		artisanedit.Hide();

		auto nl=artisaneditorganizer.nextline;

		artisaneditorganizer
			<<"Name: "<<Name<<nl
		;

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

				changed=true;
			}
		});
	}

	~UI() {
		artisanedit.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() {
		artisanedit.Hide();
		CurrentFile.New();

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

		CurrentArtisan=NULL;
		artisans.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:artisan").name="ID";

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

		ListArtisans();

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

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

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

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

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

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

		d.SetCaption(ss.str());
		d.Add(ss.str()).name="Name";


		CurrentFile.Root().Add(d);

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

		changed=true;
	}

	void SelArtisan() {
		if(artisans.GetSelectedItem()) {
			artisanedit.Show();
			CurrentArtisan=&CurrentFile.Root().Get<gorgon::DataArray>(artisans.FindLocation(artisans.GetSelectedItem())+1);
			
			auto &ci=*CurrentArtisan;
			int ind=0;

			Name.Text=ci.getString(ind++);
		}
		else {
			CurrentArtisan=NULL;
			artisanedit.Hide();
		}
	}

	void DelArtisan() {
		if(CurrentArtisan)
			CurrentFile.Root().Remove(CurrentArtisan);

		ListArtisans();

		changed=true;
	}

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

	widgets::Listbox<> artisans;
	widgets::Button newartisan;
	widgets::Button delartisan;

	widgets::InlinePanel artisanedit;
	widgets::LinearOrganizer artisaneditorganizer;

	widgets::Textbox Name;



	gorgon::File CurrentFile;
	gorgon::DataArray *CurrentArtisan;

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