/***************************** LICENSE START ***********************************

 Copyright 2012 ECMWF and INPE. This software is distributed under the terms
 of the Apache License version 2.0. In applying this license, ECMWF does not
 waive the privileges and immunities granted to it by virtue of its status as
 an Intergovernmental Organization or submit itself to any jurisdiction.

 ***************************** LICENSE END *************************************/

#include "FolderDatabase.h"

#include <iostream>
#include <fstream>

#include "Folder.h"
#include "Path.h"
#include "Tokenizer.h"

vector<FolderDatabase*> FolderDatabase::db_;

//===========================================
//
// Folderdatabase
//
//===========================================

FolderDatabase::FolderDatabase()
{
	//Home	
	char *mvhome=getenv("METVIEW_USER_DIRECTORY");
 	if(!mvhome)
	{  
		return;
	 	cout << "error in FolderDatabase" << endl;
		exit(1);		
	}	
		
	//homePath_=Folder::path(Folder::HomeFolder);
	homePath_=string(mvhome);
	
  	rootPath_=homePath_ + "/System/.icon_database";
			
  	db_.push_back(this);
}

void FolderDatabase::read()
{
	folders_.clear();;  
		
	ifstream in(dbFile_.c_str());	
	if(!in.good())
	  	return;
	
	string line;
	//getline(in,line);

	Tokenizer parse(",");
	vector<string> n;
		
	while(getline(in,line))
	{
		parse(line,n);
		if(n.size() == 2)
		{
			folders_[n[0]]=n[1];
		}
		n.clear();		
	}	
	in.close();	
}

void FolderDatabase::write()
{
	Path dbfPath(dbFile_);
	Path parent=dbfPath.directory();
	
	if(!parent.exists())
		parent.mkdir();  
		
	ofstream out(dbFile_.c_str());	
	if(!out.good())
	  	return;
	
	for(map<string,string>::iterator it=folders_.begin(); it != folders_.end(); it++)
	{
	  	out << it->first << "," << it->second << endl;
	}
	
	out.close();
}

string FolderDatabase::path(const string& name)
{
	for(vector<FolderDatabase*>::iterator it=db_.begin(); it != db_.end(); it++)
	{
	  	if((*it)->isOwner(name))
		{
		  	string p=(*it)->find(name);
			if(p.empty())
			{
			  	return (*it)->add(name);
			}
			return p;			
		}
	}
	
	return string();
}

string FolderDatabase::find(const string& name)
{	
	map<string,string>::iterator it=folders_.find(name);
	if(it != folders_.end())
	{
	  	return dbPath_ + "/" + it->second;
	}
	
	return string();	
}	
		

string FolderDatabase::add(const string& name)
{	
	string dbItem=uniquePath();
	if(!dbItem.empty())
	{
		Path p(dbPath_ + "/" + dbItem);
		p.mkdir();
		folders_[name]=dbItem;	
		write();
		return p.str();
	}
	else
	{
		cout << " db error" ;
	}
	
	return string();
}	


string FolderDatabase::uniquePath()
{
	int id=0;
	map<string,string>::const_iterator it;

	while(id < 100000)
	{  
		stringstream sst;
		sst << id;
		string name="folder_" + sst.str();
		
		bool found=false;
		for(map<string,string>::iterator it=folders_.begin(); it != folders_.end(); it++)
		{
			if(it->second  == name)
			{
			  	found=true;
				break;
			}			
		}
		
		if(!found)
		{
			return name;
		}
		
		id++;
	}
	
	return string();
}  

//===========================================
//
// Folderdatabase
//
//===========================================


InternalFolderDatabase::InternalFolderDatabase()
{  
	dbPath_=rootPath_ + "/internal";
	dbFile_=dbPath_ + "/folders";
	read();
}

bool InternalFolderDatabase::isOwner(const string& name)
{
	return (name.find(homePath_) == 0)?true:false;	  
}

ExternalFolderDatabase::ExternalFolderDatabase()
{  
  	dbPath_=rootPath_ + "/external";
	dbFile_=dbPath_ + "/folders";
	read();
}

bool ExternalFolderDatabase::isOwner(const string& name)
{
	return (name.find(homePath_) !=0 )?true:false;	  
}


static InternalFolderDatabase internalFolderDb;
static ExternalFolderDatabase externalFolderDb;
