/***************************** 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 "RequestPanelItem.h"
#include "RequestPanel.h"

#include "MvIconParameter.h"
#include "Request.h"

RequestPanelItem::RequestPanelItem(RequestPanel& owner, const MvIconParameter& param) :
    owner_(owner),
    param_(param)
{
    owner_.registerObserver(this);
    decache();
}

RequestPanelItem::~RequestPanelItem() = default;

void RequestPanelItem::set(Request&)
{
}

void RequestPanelItem::edit(IconObject* icon)
{
    currentObject_ = icon;
}

#if 0
void RequestPanelItem::getSizes(Dimension& a,Dimension& b)
{
     a = b = 0;	
}

void RequestPanelItem::setSizes(Dimension,Dimension)
{
}
#endif

long RequestPanelItem::flags()
{
    return EXPAND_2ND_NAME;
}

//void RequestPanelItem::refresh(const std::vector<std::string>&)
//{
//}

void RequestPanelItem::grey()
{
    const Request& r                = owner_.request(flags());
    std::vector<std::string> values = r.get("_UNSET");
    bool g                          = false;
    std::string name                = param_.name();
    for (auto& value : values)
        if (name == value) {
            g = true;
            break;
        }

    gray(g);
}

void RequestPanelItem::reset()
{
    const Request& r                = owner_.request(flags());
    std::vector<std::string> values = r.get(param_.name());

    bool valChanged = (values != cache_);

    if (valChanged) {
        cache_ = values;
        refresh(values);
    }

    grey();

    if (valChanged) {
        // Check defaults
        std::vector<std::string> def = owner_.request(flags() | EXPAND_NO_DEFAULT).get(param_.name());
        mark(def.size() != 0 && values.size() != 0);
    }
}


void RequestPanelItem::cleanup()
{
    visibleByTemporary_ = true;
}

void RequestPanelItem::update()
{
    reset();
}

void RequestPanelItem::checkDefault()
{
    const Request& r                = owner_.request(flags());
    std::vector<std::string> values = r.get(param_.name());
    mark(values != cache_);
}

void RequestPanelItem::apply()
{
}

void RequestPanelItem::decache()
{
    cache_.clear();
    cache_.push_back("\1\2\3");  // Something imposible
}

/*void RequestPanelItem::mark(bool)
{
}*/
