/***************************** 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 <fstream>
#include <iostream>
#include <map>
#include <string>
#include <vector>

#include "fstream_mars_fix.h"

#include <cassert>
#include <cstdlib>

#include "MvBinaryReader.h"
#include "MvMiscellaneous.h"

#include "MvFlexpart.h"

struct FxpReceptorData;

struct FxpReceptor
{
    std::string name;
    double lat{0.};
    double lon{0.};
    std::vector<FxpReceptorData> data;
};

struct FxpReceptorData
{
    FxpReceptorData(int step, double val) :
        time(step),
        val(val) {}
    int time;
    double val;
};

bool write(const std::vector<FxpReceptor>& rec, const std::string& species, const std::string& rcType,
           const std::string& outPattern);

bool convert(const std::string& headerFile, const std::string& datesFile, const std::string& recType,
             const std::string& recFile, const std::string& outPattern, int recNum)
{
    MvFlexpartHeader header(headerFile);
    MvFlexpartDates dates(datesFile);

    // dates.print();

    MvBinaryReader r(recFile);

    if (!r.isValid()) {
        std::cerr << "Could not open flexpart output receptor file: " << recFile << std::endl;
        exit(1);
    }

    std::vector<FxpReceptor> recVec;

    r.skipRecMarker();
    for (int i = 0; i < recNum; i++) {
        FxpReceptor rec;
        r.read(16, rec.name);
        recVec.push_back(rec);
        // std::cout << "name: " << rec.name << std::endl;
    }
    r.skipRecMarker();

    r.skipRecMarker();
    for (int i = 0; i < recNum; i++) {
        recVec[i].lon = r.read<float>();
        recVec[i].lat = r.read<float>();
        // std::cout << "lat: " << recVec[i].lat << std::endl;
    }
    r.skipRecMarker();

    // Create a map to hold receptor data for each species
    std::map<int, std::vector<FxpReceptor> > recMap;
    for (int spec = 0; spec < header.specNum; spec++) {
        recMap[spec] = recVec;
    }

    int stepNum = dates.num;

    for (int i = 0; i < stepNum; i++) {
        r.skipRecMarker();
        int step = r.read<int>();  // forecast time in seconds
        r.skipRecMarker();

        for (int spec = 0; spec < header.specNum; spec++) {
            r.skipRecMarker();
            std::vector<float> vals;
            r.read<float>(recNum, vals);
            r.skipRecMarker();

            for (size_t rec = 0; rec < recMap[spec].size(); rec++) {
                recMap[spec][rec].data.emplace_back(step, vals[rec]);
            }
        }
    }

    // Write one file per species
    for (int spec = 0; spec < header.specNum; spec++) {
        write(recMap[spec], std::to_string(spec + 1), recType, outPattern);
    }

    return true;
}

bool write(const std::vector<FxpReceptor>& rec, const std::string& species, const std::string& recType, const std::string& outPattern)
{
    std::ofstream out;
    std::string outFile = outPattern + species + "_.csv";
    out.open(outFile.c_str());
    if (!out.is_open()) {
        std::cerr << "Cannot open output file: " << outFile << std::endl;
        return false;
    }

    if (rec.empty()) {
        std::cerr << "No repectors was found for species=" << species << std::endl;
        return false;
    }

    // metadata
    out << "species=" << species << " type=" << recType << " receptorNum=" << rec.size();

    for (size_t i = 0; i < rec.size(); i++) {
        out << " lat_" << i + 1 << "=" << rec[i].lat << " lon_" << i + 1 << "=" << rec[i].lon;
    }

    out << std::endl;

    // header
    out << "time";
    for (size_t i = 0; i < rec.size(); i++) {
        out << ",value_" << i + 1;
    }
    out << std::endl;

    if (rec.size() == 0)
        return false;

    // Each receptor series must have the same number of times
    for (size_t i = 1; i < rec.size(); i++) {
        assert(rec[0].data.size() == rec[i].data.size());
        // Receptors series must have the same times
        for (size_t j = 0; j < rec[i].data.size(); j++)
            assert(rec[0].data[j].time == rec[i].data[j].time);
    }

    // data
    for (size_t j = 0; j < rec[0].data.size(); j++) {
        out << rec[0].data[j].time;

        for (const auto& i : rec) {
            out << "," << i.data[j].val;
        }

        out << std::endl;
    }

    return true;
}

//============================================
// Main
//============================================

int main(int argc, char** argv)
{
    if (argc != 7) {
        std::cerr << "Invalid number of arguments: " << argc << "(instead of 7)" << std::endl;
        exit(1);
    }

    std::string headerFile(argv[1]);
    std::string datesFile(argv[2]);
    std::string recType(argv[3]);
    std::string recFile(argv[4]);
    std::string outPattern(argv[5]);
    std::string str(argv[6]);

    int recNum = metview::fromString<int>(str);

    if (!convert(headerFile, datesFile, recType, recFile, outPattern, recNum))
        exit(1);

    return 0;
}
