#pragma once

#include <Widgets/Tabpanel.h>
#include <Widgets/Listbox.h>
#include <Widgets/Organizers/LinearOrganizer.h>
#include <Widgets/Textbox.h>

using namespace gge;

class FileInfo {
public:
	std::string Filename;

	FileInfo() {

	}

	FileInfo(const std::string &f) : Filename(f) {

	}
	
	bool operator <(const FileInfo &info) const {
		return Filename<info.Filename;
	}

	operator std::string() const {
		if(Filename.find_last_of('/')==Filename.npos)
			return Filename;
		else
			return Filename.substr(Filename.find_last_of('/')+1);
	}
};


class FileHandler {
	friend class UI;
public:
	FileHandler() : directory(".") {
		std::ifstream dirsetting(os::user::GetDocumentsPath()+"/.trinlibr/tools/"+Main.getSystemName()+"-directory.setting");
		if(dirsetting.is_open()) {
			std::string s;
			std::getline(dirsetting, s);
			SetDirectory(s);
		}
	}

	void SetPanel(widgets::Panel &panel) {

		this->panel=&panel;
		panel.SetOrganizer(organizer);
		organizer.Spacing=1;
		organizer.ButtonAlign=TextAlignment::Center;

		go.Text="Go";
		go.ClickEvent.RegisterLambda([&]{RefreshFiles();});
		go.SetWidth(60);

		lst.Resize(panel.GetUsableWidth(), panel.GetUsableHeight()-New.GetHeight()*3-directory.GetHeight()-12);
		lst.ItemClickedEvent.RegisterLambda([&]{ Load.Enable(); });

		New.Text="New";
		New.SetWidth(80);

		Load.Text="Load";
		Load.Disable();
		Load.SetWidth(80);

		Save.Text="Save";
		Save.SetWidth(90);
		Save.Disable();
		SaveAs.Text="Save as";
		SaveAs.SetWidth(90);
		SaveAs.Disable();

		Quit.Text="Quit";

		organizer
			<<directory<<go<<organizer.nextline
			<<lst<<organizer.nextline
			<<New<<Load<<organizer.nextline
			<<Save<<SaveAs<<organizer.nextline
			<<Quit
		;
		
	}
	
	void RefreshFiles() {
		lst.Destroy();

		utils::AddCopy(lst, os::filesystem::DirectoryIterator(directory, "*.gor"));
		lst.Sort();
		Load.Disable();

		os::filesystem::CreateDirectory(os::user::GetDocumentsPath()+"/.trinlibr/tools");
		std::ofstream file(os::user::GetDocumentsPath()+"/.trinlibr/tools/"+Main.getSystemName()+"-directory.setting");

		file<<directory.Text;
	};

	void SetDirectory(const std::string &value) {
		directory=value;
		directory.ChangeEvent();
		RefreshFiles();
	}

	~FileHandler() {
		this->panel->RemoveOrganizer();
		lst.Destroy();
	}

	widgets::Button New;
	widgets::Button Load;
	widgets::Button Quit;

protected:
	widgets::Panel *panel;
	widgets::Listbox<FileInfo> lst;
	widgets::LinearOrganizer organizer;

	widgets::Textbox directory;
	widgets::Button go;

	widgets::Button Save, SaveAs;

};
