/** \file
 *
 *  Contains the CTD_NeilBrown class declaration.
 *
 *  CTD_NeilBrown.h should only be included by CTD_NeilBrown.cpp
 *  Other classes should include CTD_NeilBrownIF.h
 *
 *  Copyright (c) 2007,2008,2009 MBARI
 *  MBARI Proprietary Information.  All Rights Reserved
 */

#ifndef CTD_NEILBROWN_H_
#define CTD_NEILBROWN_H_

#include <vector>       // std::vector

#include "component/AsyncComponent.h"
#include "io/LoadControl.h"
#include "io/UartStream.h"
#include "logger/Logger.h"
#include "utils/BinFilter1D.h"


class UniversalDataReader;
class UniversalDataWriter;


/**
 *  Software interface to Neil Brown CTD.  Also provides interface
 *  to SimSlate for providing simulated temperature, salinity, and
 *  depth.
 *
 *  \note still needs to be coded for the actual Neil Brown CTD
 *
 *  CTD_NeilBrown.h should only be included by CTD_NeilBrown.cpp
 *  Other classes should include CTD_NeilBrownIF.h
 *
 *  \ingroup modules_science
 */
class CTD_NeilBrown: public AsyncComponent
{
public:
    CTD_NeilBrown( const Module* module );
    virtual ~CTD_NeilBrown();

    virtual void run();

    /// Do what needs to be done to run
    /// Similar to initialize, in old init/run/uninit sequence
    virtual RunState start();

    /// Might follow a STOP...START sequence
    virtual RunState starting();

    /// Pause for a short period (indicated by pauseTime)
    virtual RunState pause();

    /// Should eventually follow a PAUSE request: should set continueTime
    virtual RunState paused();

    /// Resume from PAUSE
    virtual RunState resume();

    /// Might follow a PAUSE...RESUME sequence
    virtual RunState resuming();

    /// Should eventually follow a START request or RESETTING
    virtual RunState runnable();

    /// Might occur in case of Error
    virtual RunState resetting()
    {
        return stop();
    }

    /// Initial state -- can be later followed by START
    virtual RunState stop();

    virtual RunState stopping();

    /// Initial state -- can be later followed by START
    virtual RunState stopped();

    void uninitialize();

    /// Should return [myNamespace]::SIMULATE_HARDWARE, or [myNamespace]::POWER, etc
    virtual ConfigURI getConfigURI( ConfigOption configOption ) const;

private:

    // Note that the copy constructor below is private and not given a body.
    // Any attempt to call it will return a compiler error.
    CTD_NeilBrown( const CTD_NeilBrown& old ); // disallow copy constructor

    /// Async thread cycle period
    static const Timespan PERIOD;

    void readConfig();

    bool parseResponse( char *data );

    unsigned int bufferOffset_;

    UniversalDataReader* latitudeReader_;

    DataReader* gfScanActiveReader_;

    UniversalDataWriter* conductivityWriter_;
    UniversalDataWriter* densityWriter_;
    UniversalDataWriter* depthWriter_;
    UniversalDataWriter* pressureWriter_;
    UniversalDataWriter* salinityWriter_;
    UniversalDataWriter* soundSpeedWriter_;
    UniversalDataWriter* temperatureWriter_;

    DataWriter* binMedianTemperatureWriter_;
    DataWriter* binMeanTemperatureWriter_;
    DataWriter* binStandardDeviationTemperatureWriter_;
    DataWriter* binMedianSalinityWriter_;
    DataWriter* binMeanSalinityWriter_;
    DataWriter* binStandardDeviationSalinityWriter_;

    ConfigReader* maxPressBoundCfgReader_;
    ConfigReader* maxSalinityBoundCfgReader_;
    ConfigReader* minPressBoundCfgReader_;
    ConfigReader* minSalinityBoundCfgReader_;
    ConfigReader* offsetCfgReader_;


    // returns true if data is requested from one of the readers
    bool isDataRequested();

    void setWritersInvalid();

    // Debugging outputs
    bool debug_;

    // Instance of load controller
    LoadControl loadControl_;

    // the pressure reading is out of bounds. We only want to report the error once
    bool pressBoundingError_;

    /// Time data request started
    Timestamp startTime_;

    /// Timeout for getting data
    Timespan ctdTimeout_;

    static const unsigned int MAX_DEVICE_RESPONSE_SIZE = 255;
    static const unsigned short MAX_DEVICE_MSG_QUEUE_SIZE = 10;

    // Stores the current response from the device
    char deviceResponse_[MAX_DEVICE_RESPONSE_SIZE + 1];

    // Holds the communications device
    UartStream uart_;

    float latitude_;
    float conductivity_, temperature_, pressureDB_, depth_, salinity_, density_, soundSpeed_;
    bool badConductivity_, badTemperature_, badPressure_, badSalinity_;
    float pressureOffset_;
    float maxPressBound_;
    float minPressBound_;
    float maxSalinityBound_;
    float minSalinityBound_;

    // container for history to use in temporal binning
    BinFilter1D<float> temperatureBin_;
    BinFilter1D<float> salinityBin_;

    // If true, ignore next line
    bool nextLineQuestionable_;

    void go();  // What we do if we are halted.

    bool receive(); // Try receiving the data from the UART
    bool getSimulatedData(); // Try reading data from the SimSlate
    void preprocessData(); // Perform onboard processing and quality checks
    void writeData(); // write data out to the slate
    void updateTemporalBin(); // update the onboard binning
    void calculateAndReportTemporalBinStatistics(); // calculate statistics when bin is full

    // Calculates a NMEA checksum
    static int calcChecksum( const char* response );

};

#endif /* CTD_NEILBROWN_H_ */
