#include "FishIDE.h"

#include "FileTools.h"
#include "Settings.h"
#include "Dialogs.h"

// examples management

void FishIDE::OpenExample(String const &path, bool inPlace)
{
	String sourceName = GetFileTitle(path);
	if(inPlace)
	{
		projectsCtrl.OpenProject(ForceExt(AppendFileName(path, sourceName), ".ino"));
	}
	else
	{
		String destPath = AppendFileName(Settings.GetSketchFolder(), sourceName);
		bool rename = false;
		String newName = sourceName;
		if(DirectoryExists(destPath))
		{
			RenameExampleDialog dlg(newName);
			if(dlg.Run() != IDOK)
				return;
			newName = ~dlg.newName;
			destPath = AppendFileName(Settings.GetSketchFolder(), newName);
			rename = true;
		}
		if(!FileTools::DirectoryCopy(path, destPath))
		{
			Exclamation(t_("Error importing example"));
			return;
		}
		if(rename)
		{
			String src = ForceExt(AppendFileName(destPath, sourceName), ".ino");
			String dst = ForceExt(AppendFileName(destPath, newName), ".ino");
			if(!FileExists(dst))
				FileMove(src, dst);
			else
			{
				Exclamation(Format(t_("Error renaming '%s.ino' file to '%s.ino'&Please correct folder manually"), sourceName, newName));
				return;
			}
		}
		projectsCtrl.OpenProject(ForceExt(AppendFileName(destPath, newName), ".ino"));
	}
}

VectorMap<String, Vector<String>> FishIDE::GatherLibrariesExamples(String const &librariesRoot)
{
	VectorMap<String, Vector<String>> res;
	
	// get libraries from root
	Vector<String> libraries = FileTools::ScanFolder(librariesRoot, "*", true);
	
	// get each library's examples
	for(int iLibrary = 0; iLibrary < libraries.GetCount(); iLibrary++)
	{
		String libName = libraries[iLibrary];
		String exRoot = AppendFileName(librariesRoot, AppendFileName(libName, "examples"));
		Vector<String> examples = FileTools::ScanFolder(exRoot, "*", true);
		for(int i = 0; i < examples.GetCount(); i++)
			examples[i] = AppendFileName(exRoot, examples[i]);
		res.Add(libName, pick(examples));
	}
	
	return res;
}

VectorMap<String, Vector<String>> FishIDE::GatherManagedExamples(void)
{
	VectorMap<String, Vector<String>> res;

	// get categories from root
	String examplesRoot = Settings.GetExamplesRoot();
	Vector<String> categories = FileTools::ScanFolder(examplesRoot, "*", true);

	// get each category's examples
	for(int iCat = 0; iCat < categories.GetCount(); iCat++)
	{
		String catName = categories[iCat];
		String exRoot = AppendFileName(examplesRoot, catName);
		Vector<String> examples = FileTools::ScanFolder(exRoot, "*", true);
		for(int i = 0; i < examples.GetCount(); i++)
			examples[i] = AppendFileName(exRoot, examples[i]);
		res.Add(catName, pick(examples));
	}
	
	return res;
}
