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

 Copyright 2014 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 "Items.h"

#include "ConfigLoader.h"
#include "Folder.h"
#include "IconClass.h"
#include "IconObject.h"
#include "IconFactory.h"
#include "Log.h"
#include "Request.h"

static std::map<std::string, Items*> items;

Items::Items(request* r) :
    r_(r),
    object_(0)
{
    items[get_value(r, "name", 0)] = this;
}

Items::~Items() = default;

void Items::load(request* r)
{
    new Items(r);
}

void Items::createAll()
{
    for (auto& item : items) {
        item.second->object();
    }
}

void Items::objects(std::vector<IconObject*>& ret)
{
    for (auto& item : items) {
        if (item.second->object())
            ret.push_back(item.second->object());
    }
}

IconObject* Items::find(const std::string& a)
{
    // std::cout << "Items::find( " << a << std::endl;
    auto j = items.find(a);
    if (j == items.end())
        return nullptr;
    else
        return (*j).second->object();
}

IconObject* Items::object()
{
    if (object_ != 0)
        return object_;

    const char* kind = get_value(r_, "class", 0);
    const char* full = get_value(r_, "full_name", 0);
    //const char *x    = get_value(r_,"x",0);
    //const char *y    = get_value(r_,"y",0);
    const char* link = get_value(r_, "linked_to", 0);

    object_ = IconObject::search(full);
    if (object_)
        return object_;

    if (link) {
        Path path = Folder::top()->path();
        path      = path.add(full);
        path.symlink(std::string(link));
    }


    object_ = IconFactory::create(full, IconClass::find(kind));
    /*if(object_) {
		if(x && y) object_->parent()->position(object_,atol(x),atol(y));
		return object_;
	}*/

    return object_;

    Log::error(0) << "Cannot create " << full << std::endl;
    return 0;
}


static SimpleLoader<Items> loadClasses("special_folder", 1);
