/***************************** 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 <fstream>
#include <iostream>
#include <sstream>

#include "fstream_mars_fix.h"

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

std::vector<FolderDatabase*> FolderDatabase::db_;

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

FolderDatabase::FolderDatabase()
{
    // Home
    char* mvhome = getenv("METVIEW_USER_DIRECTORY");
    if (!mvhome) {
        return;
        std::cout << "error in FolderDatabase" << std::endl;
        exit(1);
    }

    // homePath_=Folder::path(Folder::HomeFolder);
    homePath_ = std::string(mvhome);

    rootPath_ = homePath_ + "/System/.icon_database";

    db_.push_back(this);
}

void FolderDatabase::read()
{
    folders_.clear();

    std::ifstream in(dbFile_.c_str());
    if (!in.good())
        return;

    std::string line;
    // getline(in,line);

    Tokenizer parse(",");
    std::vector<std::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();

    std::ofstream out(dbFile_.c_str());
    if (!out.good())
        return;

    for (auto& folder : folders_) {
        out << folder.first << "," << folder.second << std::endl;
    }

    out.close();
}

std::string FolderDatabase::path(const std::string& name)
{
    for (auto& it : db_) {
        if (it->isOwner(name)) {
            std::string p = it->find(name);
            if (p.empty()) {
                return it->add(name);
            }
            return p;
        }
    }
    return {};
}

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


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

    return {};
}


std::string FolderDatabase::uniquePath()
{
    int id = 0;
    while (id < 100000) {
        std::stringstream sst;
        sst << id;
        std::string name = "folder_" + sst.str();

        bool found = false;
        for (auto& folder : folders_) {
            if (folder.second == name) {
                found = true;
                break;
            }
        }

        if (!found) {
            return name;
        }

        id++;
    }

    return {};
}

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


InternalFolderDatabase::InternalFolderDatabase()
{
    setDbPath(rootPath() + "/internal");
    setDbFile(dbPath() + "/folders");
    read();
}

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

ExternalFolderDatabase::ExternalFolderDatabase()
{
    setDbPath(rootPath() + "/external");
    setDbFile(dbPath() + "/folders");
    read();
}

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


static InternalFolderDatabase internalFolderDb;
static ExternalFolderDatabase externalFolderDb;
