/***************************** 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 "MvQFileList.h"
#include "eccodes.h"
#include <iostream>
#include <QDebug>

QMap<MvQFileList::FileType, QString> MvQFileList::typeNames_;

MvQFileList::MvQFileList(FileType type) :
    type_(type)
{
}

MvQFileList::MvQFileList(QStringList exprLst) :
    type_(BadFile)
{
    init();

    foreach (QString s, exprLst) {
        QString err;
        add(s, err, false);
    }
}

MvQFileList::MvQFileList(QStringList exprLst, FileType type) :
    type_(type)
{
    init();

    foreach (QString s, exprLst) {
        QString err;
        add(s, err, false);
    }
}

void MvQFileList::clear()
{
    emit fileAddRemoveBegin();
    files_.clear();
    emit fileAddRemoveEnd();
}

void MvQFileList::clearOthers(QString fpath)
{
    emit fileAddRemoveBegin();

    QList<QFileInfo> newLst;
    foreach (QFileInfo f, files_)
        if (f.absoluteFilePath() == fpath)
            newLst << f;

    files_.clear();
    if (!newLst.isEmpty())
        files_ = newLst;

    emit fileAddRemoveEnd();
}

void MvQFileList::init()
{
    if (typeNames_.isEmpty()) {
        typeNames_[BufrFile] = "BUFR";
        typeNames_[GribFile] = "GRIB";
        typeNames_[OtherFile] = "OTHER";
        typeNames_[BadFile] = "BAD";
    }
}

QString MvQFileList::typeName() const
{
    return typeNames_.value(type_);
}

QStringList MvQFileList::names()
{
    QStringList lst;
    foreach (QString s, paths_) {
        QFileInfo f(s);
        lst << f.fileName();
    }

    return lst;
}

QStringList MvQFileList::paths() const
{
    QStringList lst;
    foreach (QFileInfo f, files_)
        lst << f.absoluteFilePath();

    return lst;
}

QString MvQFileList::path(int i) const
{
    Q_ASSERT(i >= 0 && i < files_.size());

    return files_.at(i).absoluteFilePath();
}

QString MvQFileList::name(int i) const
{
    Q_ASSERT(i >= 0 && i < files_.size());

    return files_.at(i).fileName();
}


bool MvQFileList::isPresent(QString path) const
{
    foreach (QFileInfo f, files_)
        if (f.absoluteFilePath() == path)
            return true;
    return false;
}

bool MvQFileList::add(QString s, QString& err, bool broadcast)
{
    if (isPresent(s)) {
        return false;
    }

    FileType type = fileType(s);
    if (type_ == BadFile) {
        if (type == BufrFile || type == GribFile) {
            type_ = type;

            if (broadcast)
                emit fileAddRemoveBegin();
            files_ << QFileInfo(s);
            if (broadcast)
                emit fileAddRemoveEnd();
            return true;
        }
    }
    else if (type_ == type) {
        if (broadcast)
            emit fileAddRemoveBegin();
        files_ << QFileInfo(s);
        if (broadcast)
            emit fileAddRemoveEnd();

        return true;
    }

    err = "Could not add file: <b>" + s + "</b> because its type is not <b>" + typeName() + "</b>!";

    return false;
}

MvQFileList::FileType MvQFileList::fileType(QString fname)
{
    codes_handle* h = nullptr;
    int err = 0, cnt = 0;
    FileType retVal = OtherFile;
    QFileInfo fInfo(fname);
    if (!fInfo.isFile())
        return BadFile;

    std::string infile = fname.toStdString();

    FILE* in = fopen(infile.c_str(), "rb");
    if (!in) {
        std::cerr << "Unable to open file " << infile << std::endl;
        return BadFile;
    }

    while ((h = codes_handle_new_from_file(nullptr, in, PRODUCT_ANY, &err)) != nullptr || err != CODES_SUCCESS) {
        if (h == nullptr) {
            std::cerr << "Unable to create handle for message " << cnt << std::endl;
            cnt++;
            continue;
        }

        size_t len = 0;
        CODES_CHECK(codes_get_length(h, "kindOfProduct", &len), nullptr);
        char* kind = (char*)malloc(len * sizeof(char));

        codes_get_string(h, "kindOfProduct", kind, &len);

        if (strcmp(kind, "BUFR") == 0)
            retVal = BufrFile;
        else if (strcmp(kind, "GRIB") == 0)
            retVal = GribFile;

        free(kind);
        codes_handle_delete(h);

        break;
    }

    fclose(in);

    return retVal;
}

MvQFileList::FileType MvQFileList::firstValidType(QStringList exprLst)
{
    foreach (QString s, exprLst) {
        FileType type = fileType(s);
        if (type != BadFile)
            return type;
    }
    return BadFile;
}
