/***************************** 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 *************************************/

//
//  Methods for the Decoder class
//  Methods for the Decoder Factory class
//
//

#include "MvDecoder.h"
#include "MvGribDecoder.h"
#include "ObjectList.h"

//==================================================================
// Decoder Factory class
//
Cached
DecoderFactoryTraits::FactoryName(const MvRequest& request)
{
    Cached factoryName = ObjectList::Find("request", request.getVerb(), "decoder");

    return factoryName;
}

Decoder*
DecoderFactoryTraits::DefaultObject(const MvRequest& request)
{
    return new GribDecoder(request);
}

//
//===================================================================
//
// Decoder class
//

Decoder::Decoder(const MvRequest&) :
    metadataRequest_("EMPTY")
{
}

Decoder::~Decoder() = default;

// Utilities for derived classes
void Decoder::AddData(MvRequest& out, std::vector<double>& dataVector, const char* outName)
{
    for (double i : dataVector)
        out.addValue(outName, i);
}

void Decoder::AddData(MvRequest& out, std::vector<std::string>& dataVector, const char* outName)
{
    for (auto& i : dataVector)
        out.addValue(outName, i.c_str());
}

void Decoder::CheckMinMax(std::vector<double>& values, double& oldMax, double& oldMin)
{
    double currMax = *(std::max_element(values.begin(), values.end()));
    double currMin = *(std::min_element(values.begin(), values.end()));

    if (currMax > oldMax)
        oldMax = currMax;
    if (currMin < oldMin)
        oldMin = currMin;
}

void Decoder::SetTitle(MvRequest& matchingRequest)
{
    const char* title = nullptr;
    if (!(title = metadataRequest_("MV_TITLE")))
        title = metadataRequest_("TITLE");

    if (title) {
        matchingRequest("TEXT_LINE_1") = title;
        matchingRequest("TEXT_LINE_COUNT") = 1;
    }
}
