/***************************** 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 "Product.h"

#include <sstream>

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

static vector<Product*> prodItems;

Product::Product(const string& path, const string& title, const string& desc, const std::set<string>& keys, bool hasImage) :
    path_(path),
    title_(title),
    description_(desc),
    keys_(keys),
    hasImage_(hasImage)
{
}

bool Product::find(const string& str)
{
    for (set<string>::iterator it = keys_.begin(); it != keys_.end(); it++) {
        if ((*it).find(str) != string::npos)
            return true;
    }

    if (title_.find(str) != string::npos) {
        return true;
    }

    return false;
}

string Product::imagePath()
{
    return path_ + "/thumbnail.png";
}

void Product::scan()
{
    if (prodItems.size() > 0)
        return;

    //search directory structure
    Folder* root = Folder::folder("products");
    if (!root)
        return;

    scan(root->path());
}


void Product::scan(const Path& dir)
{
    Path descFile(dir.add("description.txt").str());
    Path keyFile(dir.add("keywords.txt").str());
    Path imgFile(dir.add("thumbnail.png").str());

    string desc;
    std::set<string> keys;

    if (descFile.exists())
        desc = descFile.loadText();

    if (keyFile.exists()) {
        string key = keyFile.loadText();
        std::transform(key.begin(), key.end(), key.begin(), ::tolower);

        std::set<string> keys;
        istringstream iss(key);
        do {
            string s;
            iss >> s;
            keys.insert(s);
        } while (iss);
    }

    if (keyFile.exists() || descFile.exists() || imgFile.exists()) {
        prodItems.push_back(new Product(dir.str(), dir.name(), desc, keys, imgFile.exists()));
    }

    set<string> ds = dir.directories();
    for (set<string>::iterator it = ds.begin(); it != ds.end(); it++) {
        Path p(dir.add(*it));
        Product::scan(p);
    }
}


void Product::find(const string& str, vector<Product*>& res)
{
    Product::scan();

    for (vector<Product*>::iterator it = prodItems.begin(); it != prodItems.end(); it++) {
        if ((*it)->find(str)) {
            res.push_back(*it);
        }
    }
}
