/***************************** LICENSE START ***********************************

 Copyright 2014 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 "FolderInfo.h"

#include <fstream>
#include <iostream>
#include <map>
#include <sstream>
#include <string>
#include <unordered_map>
#include <vector>
#include "fstream_mars_fix.h"

#include "Folder.h"
#include "IconInfo.h"
#include "Request.h"
#include "Tokenizer.h"
#include "MvLog.h"

std::string FolderInfo::fileName_ = "._mv_iconlist_";

FolderInfo::FolderInfo(Folder* folder) :
    folder_(folder),
    checkWasDone_(false)
{
    read();
}

void FolderInfo::read()
{
    info_.clear();  //need to delete the objects!!!

    std::string path = folder_->path().add(fileName_).str();
    std::ifstream in(path.c_str());

    if (!in.good())
        return;

    std::string line;
    Tokenizer parse(",");
    std::vector<std::string> n;
    int cnt = 0;
    std::size_t pos;

    while (getline(in, line)) {
        parse(line, n);
        if (n.size() >= 4) {
            int x, y;
            std::istringstream issX(n[0]);
            issX >> x;
            std::istringstream issY(n[1]);
            issY >> y;

            auto icName = n[2];
            adjustIcName(icName);

            pos              = line.find("," + n[3]);
            std::string name = line.substr(pos + 1);

            info_[name] = new IconInfo(icName, x, y);
        }

        n.clear();
        cnt++;
    }

    in.close();
}


void FolderInfo::write()
{
    //Remove non-existing icons from info
    check();

    std::string path = folder_->path().add(fileName_).str();
    std::ofstream out;
    out.open(path.c_str());
    if (!out.good())
        return;

    for (auto& it : info_) {
        out << it.second->x() << "," << it.second->y() << "," << it.second->type() << "," << it.first << std::endl;
    }

    out.close();
}


void FolderInfo::check()
{
    //For performance reason we do it only once!
    if (checkWasDone_)
        return;

    const auto& kids = folder_->kids();
    std::vector<std::string> removeVec;
    for (auto& it : info_) {
        if (kids.find(it.first) == kids.end()) {
            removeVec.push_back(it.first);
        }
    }

    for (const auto& it : removeVec) {
        remove(it);
    }

    checkWasDone_ = true;
}

IconInfo* FolderInfo::add(const std::string& name, IconInfo* info)
{
    info_[name] = info;
    return info;
}

IconInfo* FolderInfo::add(const std::string& name, const std::string& type)
{
    IconInfo* info = find(name);

    if (!info) {
        info        = new IconInfo(type);
        info_[name] = info;
    }

    return info;
}

IconInfo* FolderInfo::add(const std::string& name, const Request& dotInfo)
{
    auto* info = new IconInfo(dotInfo);

    info_[name] = info;

    return info;
}


IconInfo* FolderInfo::find(const std::string& name)
{
    auto it = info_.find(name);
    return (it != info_.end()) ? it->second : nullptr;
}

void FolderInfo::remove(const std::string& name)
{
    auto it = info_.find(name);
    if (it != info_.end())
        info_.erase(it);
}

void FolderInfo::rename(const std::string& oldName, const std::string& newName)
{
    auto it = info_.find(oldName);
    if (it != info_.end()) {
        IconInfo* data = it->second;
        info_.erase(it);
        info_[newName] = data;
    }
}

bool FolderInfo::read(const Path& folderPath, std::map<std::string, std::string>& icons)
{
    std::string path = folderPath.add(fileName_).str();
    std::ifstream in(path.c_str());

    if (!in.good())
        return false;

    std::string line;
    Tokenizer parse(",");
    std::vector<std::string> n;
    std::size_t pos;

    while (getline(in, line)) {
        parse(line, n);
        if (n.size() >= 4) {
            pos                         = line.find("," + n[3]);
            auto icName = n[2];
            adjustIcName(icName);
            icons[line.substr(pos + 1)] = icName;
        }

        n.clear();
    }

    in.close();

    return true;
}

// Correct iconclass names for family icons. See: METV-3184.
void FolderInfo::adjustIcName(std::string& icName)
{
    static std::unordered_map<std::string, std::string> cls = {
            {"LINE_HOVM","MHOVMOELLERDATA_FAMILY"},
            {"AREA_HOVM","MHOVMOELLERDATA_FAMILY"},
            {"EXPAND_HOVM","MHOVMOELLERDATA_FAMILY"},
            {"VERTICAL_HOVM","MHOVMOELLERDATA_FAMILY"},
            {"POTT_M", "POTT_FAMILY"},
            {"POTT_P", "POTT_FAMILY"},
            {"EQPOTT_M", "POTT_FAMILY"},
            {"EQPOTT_P", "POTT_FAMILY"},
            {"SEQPOTT_M", "POTT_FAMILY"},
            {"SEQPOTT_M", "POTT_FAMILY"},
            {"GRIB_THERMO","THERMODATA_FAMILY"},
            {"BUFR_THERMO","THERMODATA_FAMILY"},
            {"ROTWIND","DIVROT_FAMILY"},
            {"DIVWIND","DIVROT_FAMILY"},
            {"UVWIND","DIVROT_FAMILY"},
            {"VELPOT","VELSTR_FAMILY"},
            {"STREAMFN","VELSTR_FAMILY"},
            {"SAMPLE_FORMULA_DOD", "SIMPLE_FORMULA_FAMILY"},
            {"SAMPLE_FORMULA_DON", "SIMPLE_FORMULA_FAMILY"},
            {"SAMPLE_FORMULA_NOD", "SIMPLE_FORMULA_FAMILY"},
            {"SAMPLE_FORMULA_NON", "SIMPLE_FORMULA_FAMILY"},
            {"SAMPLE_FORMULA_FD", "SIMPLE_FORMULA_FAMILY"},
            {"SAMPLE_FORMULA_FN", "SIMPLE_FORMULA_FAMILY"},
            {"SAMPLE_FORMULA_FDD", "SIMPLE_FORMULA_FAMILY"},
            {"SAMPLE_FORMULA_FDN", "SIMPLE_FORMULA_FAMILY"},
            {"SAMPLE_FORMULA_FND", "SIMPLE_FORMULA_FAMILY"},
            {"SAMPLE_FORMULA_FNN,", "SIMPLE_FORMULA_FAMILY"}
        };

    auto it = cls.find(icName);
    if (it != cls.end()) {
        icName = it->second;
    }
}
