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

#include <sstream>

// Constructors
ParamInfo::ParamInfo() :
    param_(0),
    level_(0.),
    date_(0.),
    expver_("_"),
    paramName_(" "),
    paramLongName_(" "),
    units_(" ")
{
    // empty
}

ParamInfo::ParamInfo(int i1, double i2, double i5, std::string ev, std::string pn, std::string pln, std::string un) :
    param_(i1),
    level_(i5),
    date_(i2),
    expver_(ev),
    paramName_(pn),
    paramLongName_(pln),
    units_(un)
{
    // empty
}

// Deletes all info about a parameter, including all space used
// for the level data.
ParamInfo::~ParamInfo()
{
    for (auto& indexe : indexes_) {
        if (indexe.second)
            delete[] indexe.second->values_;
    }
}

std::string ParamInfo::LevelTitle()
{
    std::ostringstream oss;
    oss << level_ << " hPa" << std::ends;

    return oss.str();
}

std::string ParamInfo::ExpVerTitle()
{
    if (expver_ == "_")  //-- missing ExpVer is stored as "_"
        return {""};
    else
        return std::string("Expver ") + expver_;
}

// Fill in data related to an index/entry in the IndexesMap. Generate
// the values if needed, and delete any old values from the entry.
void ParamInfo::FillIndex(double* x, const std::string& index, int n)
{
    // Save data for one entry
    auto ii = indexes_.find(index);
    if (ii == indexes_.end()) {
        double ind = atof(index.substr(12, HOV_STEPSIZE).c_str());
        indexes_[index] = new IndexesInfo(ind);
        ii = indexes_.find(index);
    }
    else {
        if ((*ii).second->values_) {
            delete[](*ii).second->values_;
            (*ii).second->values_ = nullptr;
        }
    }

    if ((*ii).second->values_ == nullptr) {
        (*ii).second->values_ = new double[n];
        for (int i = 0; i < n; i++) {
            (*ii).second->values_[i] = DBL_MAX;
        }
    }

    double* xx = (*ii).second->values_;
    for (int i = 0; i < n; i++)
        xx[i] = x[i] < DBL_MAX ? x[i] : HMISSING_VALUE;
}

void ParamInfo::AddIndex(std::string& index)
{
    if (indexes_.find(index) == indexes_.end()) {
        double ind = atof(index.substr(12, HOV_STEPSIZE).c_str());
        indexes_[index] = new IndexesInfo(ind);
    }
}
