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

#pragma once

#include <QTimer>
#include <QThread>
#include <QMutex>

#include <string>
#include <vector>
#include "eccodes.h"

class MvKeyProfile;
class MvMessageMetaData;

class MvQAbstractMessageScanner : public QThread
{
    Q_OBJECT

public:
    MvQAbstractMessageScanner(MvMessageMetaData* data, QObject* parent = 0);
    ~MvQAbstractMessageScanner();

    void startScan(MvKeyProfile* prof);
    void stopLoad();

protected slots:
    void slotLoadStartedInThread();
    void slotLoadFinishedInThread();
    void slotGuiLog(int, std::string);
    virtual void slotTotalMessageNumComputed() = 0;
    void timeout();

signals:
    void loadStarted();
    void loadFinished();
    void profileReady(MvKeyProfile*);
    void profileProgress(int);
    void guiLog(int, std::string);
    void totalMessageNumComputed();
    void profileSizeComputed();

protected:
    virtual bool useThreadForScanning(qint64 fSize) const = 0;
    virtual bool precomputeMessageNum() const             = 0;
    void run();
    void runScan(MvKeyProfile* prof);
    void finishScan();
    bool hasFinished() const;

    void clear();
    int computeTotalMessageNum();
    void prepareKeyProfile();
    virtual void loadKeyProfile(MvKeyProfile* prof);
    virtual void readMessages(MvKeyProfile* prof) = 0;
    //virtual void readMessage(MvKeyProfile* prof, codes_handle* ch, int msgCnt, int profIndex) = 0;
    void readMessageFailed(MvKeyProfile* prof, int msgCnt, int profIndex);
    void formatKeyCount(MvKeyProfile* prof, int num);
    int percentage(int, int);

    enum LogType
    {
        TaskLogType  = 0,
        ErrorLogType = 1
    };

    std::string fileName_;
    enum MessageType
    {
        BufrType,
        GribType,
        NoType
    };
    MessageType messageType_;
    int messageNum_;  //when there is a filter this can be different than totalMessageNum_
    int totalMessageNum_;
    int broadcastStep_;
    bool firstScan_;
    bool filterEnabled_;
    std::vector<off_t> filterOffset_;
    std::vector<int> filterLen_;
    std::vector<int> filterCnt_;

    MvMessageMetaData* data_;
    MvKeyProfile* prof_;
    MvKeyProfile* profLocal_;
    MvKeyProfile* profToProcess_;

    QTimer* timer_;
    bool readyEmitted_;
    bool needToStop_;
    bool startedReceived_;
    bool finishedReceived_;
    QMutex mutex_;
};
