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

 Copyright 2017 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 *************************************/

#ifndef BUFRFILTER_H
#define BUFRFILTER_H

#include <string>
#include <vector>
#include <map>

#include "MvObs.h"
#include "MvObsSet.h"
#include "BufrFilterDef.h"

#include "MvVariant.h"
#include "MvKeyCondition.h"

class BufrFilterCondition;
class MvKeyProfile;

class MvKeyValue
{
public:
    MvKeyValue() : isSet_(false) {}
    MvKeyValue(const std::string& key,MvVariant::Type type) :
        key_(key), value_(type), isSet_(false){}

    const std::string& key() const {return key_;}
    const MvVariant& value() const {return value_;}
    MvVariant::Type type() const {return value_.type();}
    void resetValue() {isSet_=false;}
    bool isSet() const {return isSet_;}
    void setValue(const MvVariant& v) {value_=v; isSet_=true;}

protected:
    std::string key_;
    MvVariant value_;
    bool isSet_;
};

class MvBufrValue
{
    friend class MvBufrConditionGroup;
    friend class MvBufrValueGroup;

public:
    MvBufrValue(const MvKeyValue& value,bool valueTypeKnown);
    MvBufrValue(const MvKeyValue& value,const MvKeyConditionDefinition& condDef,bool valueTypeKnown);
    //MvBufrValue(const MvKeyValue& value,MvKeyCondition* cond, bool valueTypeKnown);

    const std::string& keyNameWithoutRank() const {return keyNameWithoutRank_;}
    bool isSameKey(const std::string& name) const;

    void setRankCondition(MvKeyCondition* rankCond);

protected:
    void init();

    MvKeyValue value_;
    MvKeyCondition *cond_;
    MvKeyConditionDefinition condDef_;
    MvKeyCondition *rankCond_;
    bool valueTypeKnown_;
    bool hasRank_;
    std::string keyNameWithoutRank_;
};

class MvBufrValueGroup
{
public:
    MvBufrValueGroup() : includeMissingValue_(false) {}
    ~MvBufrValueGroup();

    void setIncludeMissingValue(bool b) {includeMissingValue_=b;}
    virtual void add(const MvBufrValue&);
    virtual void checkCurrentKey(MvObs* obs);
    virtual void reset();
    std::size_t size() const {return items_.size();}
    const MvKeyValue& value(int i) const {return items_[i].value_;}
    const MvKeyValue& value(const std::string& key) const;
    bool isAllValueSet() const;
    bool isNoValueSet() const;
    bool isEmpty() const {return items_.empty();}

protected:
    void adjustType(int,int);
    bool checkCurrentKey(MvObs* obs,int idx);
    bool isMissingValue(double val);
    bool isMissingValue(long val);

    std::vector<MvBufrValue> items_;
    bool includeMissingValue_;
    static long longMissingValue_;
    static double doubleMissingValue_;
};

class MvBufrConditionGroup : public MvBufrValueGroup
{
public:
    MvBufrConditionGroup() : allMatch_(true) {}

    virtual void add(const MvBufrValue&);
    bool match() const {return allMatch_;}
    void checkCurrentKey(MvObs*);
    void checkConditions(MvObs*);
    void reset();

protected:
    void updateMatchStatus();

    bool allMatch_;
};

class MvBufrStandardGroup : public MvBufrValueGroup
{
public:
    MvBufrStandardGroup() {}
    void checkCurrentKey(MvObs*);
};

class BufrFilterEngine
{
public:
    enum FilterMode {MetviewMode,EccodesMode};

    BufrFilterEngine(const std::string& inFileName,FilterMode filterMode,MvObsSetIteratorObserver* obsSetObserver);
    ~BufrFilterEngine();    

    void add(const std::string&,const std::string&);
    const std::string& value(const std::string& key,bool mustExist=true) const;
    void values(const std::string& key,std::vector<std::string>& valueVec) const;
    void clear();
    bool isExtractedDefined() const;
    void run(const BufrFilterDef& def,const std::string& resFileName,MvKeyProfile* result);

    MvObsSetIterator* obsIter() const {return obsIter_;}

    void toGeopoints(const std::string& fName);

protected:

    //NR_returnObs  /**< - return the next available subset (from this or the next BUFR msg */
    //NR_returnMsg  /**< - return the first subset from the next BUFR message */

    enum CollectMode {CollectFirst,CollectAll};
    enum OutType {BufrOutput,CsvOutput, NoOutput};

    void getOutputOptions();
    void getIndexOptions();
    void getEditionOptions();
    void getTypeOptions();
    void getIdentOptions();
    void getTimeOptions();
    void getAreaOptions();
    void getCustomOptions();
    bool getRank(const std::string& rankKey,std::string& rankValue) const;
    bool getRanks(const std::string& rankKey,std::vector<int>& rankValue) const;

    void buildConditionDef(const std::string& key,const std::string& operKey,
                                    const std::string& valueKey,MvKeyConditionDefinition& condDef);

    bool isNumber(const std::string& val) const;
    bool isKeyValueNumber(const std::string& key) const;
    void intValue(const std::string& key,
                      const std::string& param,
                      int minVal,int& outVal) const;
    void getIntValues(const std::string& key,
                      const std::string& param,
                      int minVal,std::vector<int>& outVec) const;
    void getDoubleValues(const std::string& key,
                      const std::string& param,
                      double minVal,std::vector<double>& outVec) const;    
    void getStringValues(const std::string& key,
                                     const std::string& param,
                                     std::vector<std::string>& outVec) const;

    void filterOne();
    void addToResult(MvObs*);
    void close();

    bool parseDate(const std::string& val,int& year, int& month, int& day, std::string& err) const;
    bool parseTime(const std::string& val,int& hour,int& minute,int& second,std::string& err) const;
    bool checkHour(int h,std::string& err) const;
    bool checkMinute(int m,std::string& err) const;
    bool checkSecond(int s,std::string& err) const;
    bool parseTimeWindow(std::string& winVal,int& winSec,std::string& err) const;
    bool checkLon(float lon1,float lon2,std::string& err) const;
    bool checkLat(float lat1,float lat2,std::string& err) const;

    FilterMode filterMode_;
    MvObsSet* inObs_;
    MvObsSet* outBufr_;
    mutable MvObsSetIterator* obsIter_;
    MvObs currentObs_;
    std::string inFileName_;
    int msgCnt_;
    mutable ENextReturn obsOrMsg_;
    BufrFilterDef def_;
    OutType outType_;
    MvBufrConditionGroup coordCond_;
    MvBufrValueGroup location_;
    MvBufrValueGroup extracted_;
    bool extractedHasRank_;
    MvBufrConditionGroup customCond_;
    MvKeyProfile* result_;
    CollectMode collectMode_;
    bool includeMissingValue_;
};

#endif // BUFRFILTER_H
