/***************************** 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"),
    offset_(0),
    nextData_(false)
{
}

Decoder::~Decoder()
{
}

// Utilities for derived classes
void Decoder::AddData(MvRequest& out, vector<double>& dataVector, const char* outName)
{
    for (unsigned int i = 0; i < dataVector.size(); i++)
        out.addValue(outName, dataVector[i]);
}

void Decoder::AddData(MvRequest& out, vector<string>& dataVector, const char* outName)
{
    for (unsigned int i = 0; i < dataVector.size(); i++)
        out.addValue(outName, dataVector[i].c_str());
}

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

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

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

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