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

#include "MvBufrEdition.h"
#include "LogHandler.h"
#include "MvMiscelaneous.h"

#include <fstream>
#include <sstream>
#include <iomanip>
#include <algorithm>
#include <stdlib.h>
#include <assert.h>

std::string MvEccBufrMessage::definitionsDir_;

#define MV_CODES_CHECK_HEADER(a,msg) ({if(codesCheck(#a,__FILE__,__LINE__,a,msg) == false) {headerValid_=false;}})
#define MV_CODES_CHECK(a,msg) codesCheck(#a,__FILE__,__LINE__,a,msg)

//=========================================================
//
// MvEccBufrMessage
//
//=========================================================

MvEccBufrMessage::MvEccBufrMessage(codes_handle* h,int index) :
    index_(index), headerValid_(true), dataValid_(true),
    dataCategory_(-1),dataSubCategory_(-1),
    subsetNum_(-1), compressed_(false), hasSection2_(false), edition_(0),
    offset_(0), totalLenght_(0)
{
    if(!h)
        return;
    
    const int  MAX_CHAR_LEN=1024;
    long longVal;
    char charVal[MAX_CHAR_LEN];
    size_t vlen=0;

    MV_CODES_CHECK_HEADER(codes_get_long(h,"dataCategory",&dataCategory_),0);
    MV_CODES_CHECK_HEADER(codes_get_long(h,"dataSubCategory",&dataSubCategory_),0);

    //Edition
    long masterNumber, masterVersion,localVersion,centre,subCentre;
    MV_CODES_CHECK_HEADER(codes_get_long(h,"masterTableNumber",&masterNumber),0);
    MV_CODES_CHECK_HEADER(codes_get_long(h,"masterTablesVersionNumber",&masterVersion),0);
    MV_CODES_CHECK_HEADER(codes_get_long(h,"localTablesVersionNumber",&localVersion),0);
    MV_CODES_CHECK_HEADER(codes_get_long(h,"bufrHeaderCentre",&centre),0);
    MV_CODES_CHECK_HEADER(codes_get_long(h,"bufrHeaderSubCentre",&subCentre),0);
    edition_=MvBufrEdition::find(masterNumber,masterVersion,localVersion,centre,subCentre);
    assert(edition_);

    //Subsets
    MV_CODES_CHECK_HEADER(codes_get_long(h,"numberOfSubsets",&subsetNum_),0);
    MV_CODES_CHECK_HEADER(codes_get_long(h,"compressedData",&longVal),0);
    if(longVal == 1)
        compressed_=true;

    //Unexpanded descriptors
    MV_CODES_CHECK_HEADER(codes_get_size(h, "unexpandedDescriptors", &vlen),0);
    if(vlen > 0)
    {
        long* descriptors = (long*)malloc(vlen*sizeof(long));
        MV_CODES_CHECK_HEADER(codes_get_long_array(h, "unexpandedDescriptors", descriptors, &vlen),0);
        for(size_t i = 0; i < vlen; i++)
        {
            unexpanded_.push_back(descriptors[i]);
        }
        free(descriptors);
    }

    //tables
    vlen=MAX_CHAR_LEN;
    if(MV_CODES_CHECK(codes_get_string(h,"tablesMasterDir",charVal,&vlen),0))
    {
        tablesMasterDir_=charVal;
    }

    vlen=MAX_CHAR_LEN;
    if(MV_CODES_CHECK(codes_get_string(h,"tablesLocalDir",charVal,&vlen),0))
    {
        tablesLocalDir_=charVal;
    }

    vlen=MAX_CHAR_LEN;
    if(MV_CODES_CHECK(codes_get_string(h,"rootTablesDir",charVal,&vlen),0))
    {
        rootTablesDir_=charVal;
    }

    replace(tablesMasterDir_,"[masterTableNumber]",masterNumber);
    replace(tablesMasterDir_,"[masterTablesVersionNumber]",masterVersion);
    replace(tablesLocalDir_,"[masterTableNumber]",masterNumber);
    replace(tablesLocalDir_,"[localTablesVersionNumber]",localVersion);
    replace(tablesLocalDir_,"[bufrHeaderCentre:l]",centre);
    replace(tablesLocalDir_,"[bufrHeaderSubCentre]",subCentre);

    if(definitionsDir_.empty())
    {
        if(char* defPath=codes_definition_path(NULL))
            definitionsDir_=std::string(defPath);
    }

    tablesMasterDir_=definitionsDir_ + "/" + tablesMasterDir_;
    tablesLocalDir_=definitionsDir_+ "/" + tablesLocalDir_;
}      
 
MvEccBufrMessage::~MvEccBufrMessage()
{
}

int MvEccBufrMessage::centre() const {return edition_->centre();}
int MvEccBufrMessage::subCentre() const {return edition_->subCentre();}
int MvEccBufrMessage::masterTablesNumber() const {return edition_->masterTablesNumber();}
int MvEccBufrMessage::masterTablesVersionNumber() const {return edition_->masterTablesVersionNumber();}
int MvEccBufrMessage::localTablesVersionNumber() const {return edition_->localTablesVersionNumber();}

void MvEccBufrMessage::replace(std::string& str,const std::string& pattern,const std::string& newPattern )
{
    std::size_t pos=str.find(pattern);
    if(pos != std::string::npos)
    {
        str.replace(pos,pattern.size(),newPattern);
    }
}

void MvEccBufrMessage::replace(std::string& str,const std::string& pattern,int newPattern)
{
    std::stringstream ss;
    ss << newPattern;
    replace(str,pattern,ss.str());

}

void MvEccBufrMessage::checkPar(int err,const std::string& name)
{
    if(err != CODES_SUCCESS)
    {
        GuiLog().error() << "Could not read key " << name  << " for message " << index_
                         << ": " <<  std::string(grib_get_error_message(err)) << "\n";       
    }
}

bool MvEccBufrMessage::codesCheck(const char* call,const char* /*file*/,int /*line*/,int e,const char* /*msg*/)
{
    if(e)
    {
        const char* m=grib_get_error_message(e);
        GuiLog().error() << call << m;
        headerErrors_.push_back(std::string(call) + " " + std::string(m));
        return false;
    }
    return true;
}

const std::vector<int>&  MvEccBufrMessage::unexpandedDesc() const
{
    return unexpanded_;
}

//=========================================================
//
// MvEccBufr
//
//=========================================================

MvEccBufr::MvEccBufr(const std::string& path) :
  fileName_(path),
  messageNum_(0)
{
    messageNum_=computeMessageNum();
}    

int MvEccBufr::computeMessageNum()
{
    FILE* fp;
    fp = fopen(fileName_.c_str(),"r");
    if(!fp)
    {
            //log->error("GribMetaData::readMessages() ---> Cannot open grib file: \n        " + fileName_ + "\n");
            return 0;
    }

    int res=0;
    if(codes_count_in_file(0,fp,&res) != CODES_SUCCESS)
        res=0;

    fclose(fp);
    return res;
}

int MvEccBufr::scan()
{
     FILE* in = NULL;

     codes_handle* h=NULL;
     int err=0, cnt=0;

     in=fopen(fileName_.c_str(),"r");
     if (!in) {
         printf("ERROR: unable to open file %s\n", fileName_.c_str());
         return 1;
     }

     while ((h = codes_handle_new_from_file(NULL,in,PRODUCT_BUFR,&err)) != NULL || err != CODES_SUCCESS)
     {
         MvEccBufrMessage* m=new MvEccBufrMessage(h,cnt);
         msg_.push_back(m);
            
         if(h == NULL) {
             printf("Error: unable to create handle for message %d\n",cnt);
         }
         else 
         {
            codes_handle_delete(h);
         }
         cnt++;
     }

     fclose(in);
     return 0;
}

MvEccBufrMessage* MvEccBufr::message(int cnt)
{
   return NULL;
}

MvEccBufr::ElementDefType MvEccBufr::elementDefType(int elem)
{
    if(elem > 0 && elem < 64255)
    {
        int cat=elem/1000;
        int code=elem%1000;
        if(cat >=0 && cat <=63 && code >= 1 && code <=255)
        {
            if(cat < 48 and code < 192)
                return WmoElement;
            else
                return LocalElement;
        }
    }
    return UnknownElement;
}

bool MvEccBufr::codesCheck(const char* call,const char*  file,int line,int e,const char* msg)
{
    if(e)
    {
        GuiLog().error() << call << grib_get_error_message(e);
        return false;
    }
    return true;
}

//=========================================================
//
// MvBufrCodeTable
//
//=========================================================

std::vector<MvBufrCodeTable*> MvBufrCodeTable::tables_;

MvBufrCodeTable::MvBufrCodeTable(int element,MvBufrEdition* edition,const std::string& path) :
    element_(element),
    edition_(edition)
{
    load(path);
    tables_.push_back(this);
}

const std::string& MvBufrCodeTable::value(int code) const
{
    static std::string es;
    std::map<int,std::string>::const_iterator it=items_.find(code);
    return (it != items_.end())?it->second:es;
}

MvBufrCodeTable* MvBufrCodeTable::find(int element,MvEccBufrMessage *msg)
{
    for(std::vector<MvBufrCodeTable*>::const_iterator it=tables_.begin(); it != tables_.end(); ++it)
    {
        if((*it)->element_ == element && (*it)->edition_ == msg->edition())
            return *it;
    }

    return make(element,msg);
}

std::string MvBufrCodeTable::buildFileName(int element,const std::string& path)
{
    return path + "/codetables/" + metview::toString<int>(element) + ".table";
}

MvBufrCodeTable* MvBufrCodeTable::make(int element,MvEccBufrMessage *msg)
{
    //Try
    std::string path;
    switch(MvEccBufr::elementDefType(element))
    {
        case MvEccBufr::WmoElement:
            path=msg->tablesMasterDir();
            break;
        case MvEccBufr::LocalElement:
            path=msg->tablesLocalDir();
            break;
        default:
            return 0;
            break;
    }

    //Check if the file exists and can be open for read!
    std::string fname=buildFileName(element,path);
    std::ifstream in(fname.c_str(), std::ios::in);
    if(in.is_open())
    {
        in.close();
        MvBufrCodeTable* t=new MvBufrCodeTable(element,msg->edition(),path);
        return t;
    }
    return 0;
}


void MvBufrCodeTable::load(const std::string& path)
{
    std::string fname=buildFileName(element_,path);

    std::ifstream in(fname.c_str(), std::ios::in);
    if(!in.is_open())
    {
        std::cout << "Cannot open input file: " << fname << std::endl;
        return;
    }

    std::string line;
    while(getline(in,line))
    {
        int code;
        std::stringstream sst(line);
        sst >> code >> code;
        std::string val;
        getline(sst,val);
        items_[code]=val;
    }
}


const std::string& MvBufrFlagInfo::bitPosition(int i) const
{
    if(i >=0 && i < static_cast<int>(flags_.size()))
        return flags_[i].first;

    static std::string es;
    return es;
}

const std::string& MvBufrFlagInfo::description(int i) const
{
    if(i >=0 && i < static_cast<int>(flags_.size()))
        return flags_[i].second;

    static std::string es;
    return es;
}

//=========================================================
//
// MvBufrFlagTable
//
//=========================================================

std::vector<MvBufrFlagTable*> MvBufrFlagTable::tables_;

MvBufrFlagTable::MvBufrFlagTable(int element,MvBufrEdition* edition,const std::string& path) :
    element_(element),
    edition_(edition)
{
    load(path);
    tables_.push_back(this);
}

void MvBufrFlagTable::values(int code,int width,MvBufrFlagInfo &v) const //std::vector<std::parstd::string>& vals) const
{
    std::vector<int> bits;
    getBits(code,width,bits);

    std::string bitStr;
    size_t n=bits.size();
    for(size_t i=0; i < n; i++)
        bitStr+=(bits[i]==0)?"0":"1";

    v.bits_=bitStr;

    for(size_t i=0; i < n; i++)
    {
        if(bits[i] == 1)
        {
            std::map<int,std::string>::const_iterator it=items_.find(i+1);
            std::string desc;
            if(it != items_.end())
            {
                desc=it->second;
            }
            v.flags_.push_back(std::make_pair(metview::toString<int>(i+1),desc));
        }
    }
}

void MvBufrFlagTable::getBits(unsigned int code,int width,std::vector<int>& v)
{
    for (unsigned int mask=0x1; mask; mask<<=1)
    {
        v.push_back((code & mask) ? 1 : 0);
        if(static_cast<int>(v.size()) == width)
            break;
    }

    std::reverse(v.begin(),v.end());
}


MvBufrFlagTable* MvBufrFlagTable::find(int element,MvEccBufrMessage *msg)
{
    for(std::vector<MvBufrFlagTable*>::const_iterator it=tables_.begin(); it != tables_.end(); ++it)
    {
        if((*it)->element_ == element && (*it)->edition_ == msg->edition())
            return *it;
    }

    return MvBufrFlagTable::make(element,msg);
}

std::string MvBufrFlagTable::buildFileName(int element,const std::string& path)
{
    return path + "/codetables/" + metview::toString<int>(element) + ".table";
}

MvBufrFlagTable* MvBufrFlagTable::make(int element,MvEccBufrMessage *msg)
{
    //Try
    std::string path;
    switch(MvEccBufr::elementDefType(element))
    {
        case MvEccBufr::WmoElement:
            path=msg->tablesMasterDir();
            break;
        case MvEccBufr::LocalElement:
            path=msg->tablesLocalDir();
            break;
        default:
            return 0;
            break;
    }

    //Check if the file exists and can be open for read!
    std::string fname=buildFileName(element,path);
    std::ifstream in(fname.c_str(), std::ios::in);
    if(in.is_open())
    {
        in.close();
        MvBufrFlagTable* t=new MvBufrFlagTable(element,msg->edition(),path);
        return t;
    }
    return 0;
}

void MvBufrFlagTable::load(const std::string& path)
{
    std::string fname=buildFileName(element_,path);

    std::ifstream in(fname.c_str(), std::ios::in);
    if(!in.is_open())
    {
        std::cout << "Cannot open input file: " << fname << std::endl;
        return;
    }

    std::string line;
    while(getline(in,line))
    {
        int code;
        std::stringstream sst(line);
        sst >> code >> code;
        std::string val;
        getline(sst,val);
        items_[code]=val;
    }
}

