/***************************** 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 <Metview.h>
#include <MvTimeSerie.h>
#include <stdarg.h>

MvRequest MvTimeSerie::empty;

MvTimeSerie::MvTimeSerie(MvRequest& vaxis, MvRequest& graph) :
    Header("MAGICS_PARAMETERS"),
    HAxis("PAXIS"),
    VAxis(vaxis),
    PGraph(graph),
    user_axis(0)
{
    init();
}


void MvTimeSerie::init()
{
    Xmin              = MvDate(22020202.0);  //-- far-away in the future
    Xmax              = MvDate(18880808.0);  //-- far-away in the past
    Ymin              = 1e300;
    Ymax              = -1e300;
    NbPoints          = 0;
    reqOutFilterLevel = eTsReqsAll;

    Header("SUBPAGE_Y_POSITION")   = 1.7;
    Header("SUBPAGE_ASPECT_RATIO") = 3;

    HAxis("AXIS_TYPE")        = "DATE";
    HAxis("AXIS_DATE_TYPE")   = "DAYS";
    HAxis("AXIS_ORIENTATION") = "HORIZONTAL";
    HAxis("AXIS_GRID")        = "ON";
    HAxis("AXIS_GRID_COLOUR") = "BLACK";
}

MvRequest MvTimeSerie::getRequest()
{
    double diff = (Ymax - Ymin) * 0.1;
    int maxi, mini;
    int step, scale;
    static int nice[] = {1, 2, 3};

    Ymax  = Ymax + (diff * 0.05);
    Ymin  = Ymin - (diff * 0.05);
    scale = 1;

    for (int i = 0; i < 5; i++) {
        for (int j = 0; j < 3; j++) {
            maxi = (int)(Ymax + 0.999);
            mini = (int)(Ymin - 0.999);
            step = nice[j] * scale;
            while ((mini % step) != 0)
                mini--;
            while ((maxi % step) != 0)
                maxi++;
            if ((((maxi - mini) / step) + 1) < 5) {
                i = 5;
                break;
            }
        }
        scale = scale * 10;
    }
    Ymax = maxi;
    Ymin = mini;

    if (!VAxis) {
        VAxis                       = "PAXIS";
        VAxis("AXIS_MIN_VALUE")     = Ymin;
        VAxis("AXIS_MAX_VALUE")     = Ymax;
        VAxis("AXIS_TICK_INTERVAL") = (Ymin - Ymax) / 5;
    }

    VAxis("AXIS_ORIENTATION") = "VERTICAL";

    if (reqOutFilterLevel == eTsReqsAll)
        return Header + VAxis + HAxis + Data;
    else
        return HAxis + Data;
}

void MvTimeSerie::createNewGroup(const Cached& id, const char* legend)
{
    MvRequest curve("CURVE");
    MvRequest magics("PGRAPH");

    NbPoints = 0;

    curve("_ID") = id;

    if (PGraph)
        magics = PGraph;
    else {
        magics("GRAPH_TYPE")         = "CURVE";
        magics("GRAPH_CURVE_METHOD") = "ROUNDED";
    }

    if (legend && !(const char*)magics("LEGEND_USER_TEXT")) {
        magics("LEGEND")           = "ON";
        magics("LEGEND_USER_TEXT") = legend;
    }

    if (reqOutFilterLevel == eTsReqsCurveOnly)
        Data = Data + curve;
    else
        Data = Data + curve + magics;
}

void MvTimeSerie::addIconInfo(const Cached& ref, const Cached& param, MvRequest& r)
{
    while (Data) {
        Cached id = (const char*)Data("_ID");
        if (id == ref) {
            Data("_NAMES") += (const char*)r("_NAME");
            Data("_CLASSES") += (const char*)r("_CLASS");
            Data("_PARAMS") += param;
            break;
        }
        Data.advance();
    }
    Data.rewind();
}

void MvTimeSerie::addPoint(const Cached& ref, double x, double y)
{
    MvDate d = BaseDate + (double)x / 24.0;

    while (Data) {
        Cached id = (const char*)Data("_ID");
        if (id == ref) {
            Data("X") += d.magicsDate().c_str();
            Data("Y") += y;
            break;
        }
        Data.advance();
    }
    Data.rewind();

    if (y > Ymax) {
        Ymax = y;
    }
    if (y < Ymin) {
        Ymin = y;
    }

    if (d > Xmax) {
        Xmax                         = d;
        HAxis("AXIS_DATE_MAX_VALUE") = Xmax;
    }
    if (d < Xmin) {
        Xmin                         = d;
        HAxis("AXIS_DATE_MIN_VALUE") = Xmin;
    }
    if (Xmin.time_interval_days(Xmax) > 180) {  //-- ~ 6 months
        HAxis("AXIS_DATE_TYPE") = "MONTHS";
    }

    NbPoints++;
}

MvTimeSerie::~MvTimeSerie()
{
}

void MvTimeSerie::setDate(int date, int o)
{
    MvDate d((double)date + (double)o / 24.0);
    setDate(d);
}

void MvTimeSerie::setDate(const MvDate& d)
{
    BaseDate                     = d;
    string magDate               = d.magicsDate();
    HAxis("AXIS_DATE_MIN_VALUE") = magDate.c_str();
    Offset                       = BaseDate.Hour();
}

void MvTimeSerie::setTitle(const Cached& ref, const char* fmt, ...)
{
    char buffer[1024];
    va_list list;

    va_start(list, fmt);
    vsprintf(buffer, fmt, list);
    va_end(list);

    while (Data) {
        Cached id = (const char*)Data("_ID");
        if (id == ref) {
            Data("TITLE") += buffer;
            break;
        }
        Data.advance();
    }
    Data.rewind();
}
