#ifndef DCIPFILTER_H
#define DCIPFILTER_H

#include <QObject>
#include <QRegExp>
#include <QHash>
#include <QFile>

#ifdef _DEBUG_
#include <QtDebug>
#endif

enum eDIRECTION {
    eDIRECTION_IN = 0,
    eDIRECTION_OUT,
    eDIRECTION_BOTH
};

enum eTableAction{
    etaDROP=0,
    etaACPT
};

typedef struct _IPFilterElem{
    quint32 ip;
    quint32 mask;

    eDIRECTION direction;
    eTableAction action;
} IPFilterElem;

typedef QMultiHash<quint32, IPFilterElem*> QIPHash;
typedef QList<IPFilterElem*> QIPList;

class DCIPFilter : public QObject {
    Q_OBJECT

public:
    /** */
    DCIPFilter();
    /** */
    virtual ~DCIPFilter();

    /** */
    static quint32 StringToUint32(const QString&);
    /** */
    static QString Uint32ToString(quint32);
    /** */
    static quint32 MaskToCIDR(quint32);
    /** */
    static quint32 MaskForBits(quint32);
    /** */
    static bool ParseString(QString, quint32&, quint32&, eTableAction&);
    /** */
    static bool isIP(QString &exp);

    /** */
    void loadList();
    /** */
    void saveList();

    /** */
    const QIPList &getRules();
    /** */
    const QIPHash &getHash ();

    /** */
    void addToRules(QString exp, eDIRECTION direction);
    /** */
    void remFromRules(QString exp, eTableAction);
    /** */
    void changeRuleDirection(QString exp, eDIRECTION, eTableAction);
    /** */
    void clearRules();

    /** */
    bool OK(const QString &exp, eDIRECTION direction);

    /** */
    void exportTo(QString path);
    /** */
    void importFrom(QString path);

    /** */
    static void SetInstance(DCIPFilter*);
    /** */
    static DCIPFilter *Instance();

#ifdef _DEBUG_
    void printHash();
#endif

private:
    /** */
    QIPHash list_ip;
    /** */
    QIPList rules;
    /** */
    static DCIPFilter *pIPFilter;

signals:
    void ruleAdded(QString, eDIRECTION);
    void ruleRemoved(QString, eDIRECTION, eTableAction);
    void ruleChanged(QString, eDIRECTION, eDIRECTION, eTableAction);
};

/** */
inline void DCIPFilter::SetInstance(DCIPFilter *filter) {
    pIPFilter = filter;
}

/** */
inline DCIPFilter *DCIPFilter::Instance() {
    return pIPFilter;
}

#endif // DCIPFILTER_H
