//-----------------------------------------------------------------------------------
// <copyright file="SSQCommunicator.h" company="LiquidRobotics">
//
// Copyright (c) 2014 Liquid Robotics, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
// This software is associated with a release.  Liquid Robotics makes no
// representation that the design, interfaces or component distribution will
// remain unchanged in future releases.
//
// </copyright>
//
// <summary>
// Declarations for the SSQCommunicator class, which oversees the communication with
// the SBD modem using the SBDModem class.  After construction and successful
// initialization, the background thread continually attempts to establish
// communication with the modem and executes sessions:
//
// - The client invokes RequestSession to indicate when there are messages waiting
//   to be sent
// - The client is signaled whenever a packet is successfully received
// - The client is signaled whenever a session is about to be executed in order to
//   provide data to be sent; if the supplied packet is empty, no session is
//   executed.  The client can request a non-default mailbox check using this method.
// - The client is signaled when a packet is successfully transmitted.
// - The client is signaled with statistics whenever statistics change.
// </summary>
//
// <owner>Mike Cookson</owner>
//-----------------------------------------------------------------------------------

#ifndef __SSQCOMMUNICATOR_H__
#define __SSQCOMMUNICATOR_H__

#include "LqrSMACByteArray.h"
#include "LqrSMACDeclareException.h"
#include "LqrSMACLockableConcept.h"
#include "LqrSMACSharedLib.h"
#include "LqrSMACSemaphore.h"
#include "LqrSMACTimeCounter.h"
#include "SBDModem.h"
#include "SBDModemSettings.h"
#include "SSQCommunicatorSettings.h"
#include <stdexcept>
#include <boost/shared_ptr.hpp>
#include <boost/thread.hpp>

namespace LiquidRobotics {

namespace SMACFramework {
    class Logger;
}

namespace SimpleSBDQueue {

class SSQCommunicatorSettings;

class SHARED_LIB_PUBLIC SSQCommunicator
: public LiquidRobotics::SMACFramework::LockableConceptMutex
{
public:

    DECLARE_EXCEPTION(ShutdownRequested, std::runtime_error);

    typedef LiquidRobotics::SMACFramework::ByteArray ByteArray;
    typedef unsigned long CookieType;
    typedef LiquidRobotics::SMACFramework::ILockableConcept ILockableConcept;
    typedef LiquidRobotics::SMACFramework::LockableConceptMutex LockableConceptMutex;
    typedef LiquidRobotics::SMACFramework::Logger Logger;
    typedef boost::shared_ptr<SSQCommunicator> Ptr;
    typedef LiquidRobotics::PPPHostLib::SBDModem SBDModem;
    typedef LiquidRobotics::PPPHostLib::SBDModemSettings SBDModemSettings;
    typedef std::string string;
    typedef LiquidRobotics::SMACFramework::TimeCounter TimeCounter;

	//! Defines a type of callback signal that delivers received packets
    typedef boost::signals2::signal<void (SSQCommunicator& sender, const ByteArray& packetData, unsigned MTMSN) > ReceivedDataSignalType;

	//! Defines a type of callback signal that requests data to be sent, with the option to request a faster mailbox check
    typedef boost::signals2::signal<void (SSQCommunicator& sender, size_t maxPacketSize, ByteArray& packetData, CookieType& cookie,
                                        unsigned& newMailboxCheckTimeMS) > RequestDataToSendSignalType;

	//! Defines a type of callback signal indicates successful message transmission
    typedef boost::signals2::signal<void (SSQCommunicator& sender, CookieType cookie, unsigned MOMSN) > SentDataSignalType;

    struct Statistics
    {
	    Statistics();

	    bool operator==(const Statistics& other) const;
	    bool operator!=(const Statistics& other) const;
	    string ToString() const;

	    bool communicating;                 //!< true if successfully talking to modem, false if not
	    bool networkOK;                     //!< true if the last operation connected to the network all the way through, false if no network on startup or network lost
	    bool accessOK;                      //!< true if the last operation was able to access resource, false if access was denied
	    string model;                       //!< the model name of the modem (for example, 9603 or 9523)
	    string serialNum;                   //!< the serial number of the modem (IMEI)
	    string simNum;                      //!< the SIM card number of the modem (CICCID)
	    unsigned numSent;                   //!< the number of messages successfully sent
	    unsigned numReceived;               //!< the number of messages received
	    unsigned numSessions;               //!< the number of sessions executed
	    unsigned numSessionsSuccessful;     //!< the number of sessions that were successfully executed
	    bool reliable;                      //!< true if reliable, false if not
	    bool networkTimeout;              //!< ture if network timeout, false if not 
	    unsigned networkTimeoutStart;       //!< keep track of the timeout
    };

	//! Defines a type of callback signal indicates the status of modem
    typedef boost::signals2::signal<void (SSQCommunicator& sender, const Statistics& stats) > StatisticsSignalType;

	//! This is a synonym for the boost scoped_connection data type, which holds a subscription to an event/signal; the subscription is deleted when variable instance goes out of scope
	typedef boost::signals2::scoped_connection ScopedConnection;

	//! Smart pointer for ScopedConnection
	typedef boost::shared_ptr<ScopedConnection> ScopedConnectionPtr;

	//! SSQCommunicator constructor
    SSQCommunicator(const SSQCommunicatorSettings& _settings, Logger& _logger);

	//! SSQCommunicator destructor
    virtual ~SSQCommunicator();

	//! Initializes the instance and launches resources like threads (call after construction but before other methods)
    virtual void Initialize();

    //! Shuts down the instance and releases resources (call before destruction)
    virtual void Shutdown();

    //! Saves world position for use in SBDIX
    virtual void SetPosition(double lat, double lon);

	//! Returns the semaphore that should be locked before deleting the class instance (i.e. using ILockableConceptMutex::Lock) to prevent a potential deadlock
	virtual LockableConceptMutex& GetEventLock();

	//! Requests the communicator to call back for packet data since one or more packets are available
    virtual void RequestSession();

    //! Subscribes to the event that reports incoming data packets
    virtual ScopedConnectionPtr SubscribeReceivedData(ReceivedDataSignalType::slot_type slot);

    //! Subscribes to the event that requests more data to be sent
    virtual ScopedConnectionPtr SubscribeRequestDataToSend(RequestDataToSendSignalType::slot_type slot);

    //! Subscribes to the event that reports when data successfully sent
    virtual ScopedConnectionPtr SubscribeSentData(SentDataSignalType::slot_type slot);

    //! Subscribes to the event that reports statistics from the modem
    virtual ScopedConnectionPtr SubscribeStatistics(StatisticsSignalType::slot_type slot);

private:

    typedef LiquidRobotics::SMACFramework::Semaphore Semaphore;
    typedef boost::thread Thread;
	typedef boost::shared_ptr<Thread> ThreadPtr;

	//! Executes call-in scenario when flagged
    void Background();

    void DeallocateModem();
    void DoWait(Semaphore::Lock& lock, TimeCounter& tc, unsigned limit, const string& description);
    bool GetSavedPosition(double& lat, double& lon);
    void InitializeModem(Semaphore::Lock& lock);
    void PowerModem(bool powerOn);
    static size_t TransmitBufferSizeFromModel(const string& model);
    void Fire_ReceivedData(const ByteArray& packetData, unsigned MTMSN);
    void Fire_RequestDataToSend(size_t maxPacketSize, ByteArray& packetData, CookieType& cookie, unsigned& newMailboxCheckTimeMS);
    void Fire_SentData(CookieType cookie, unsigned MOMSN);
    void Fire_Statistics(Statistics& newValue, bool onlyOnChange = true);
    double GetCurrentTime();
    void OnRingIndicator(SBDModem& sender);

    SSQCommunicatorSettings settings;                       //!< Reference to settings for the class (values may change during operation)
    Logger& logger;                                         //!< Reference to logger for output
    LockableConceptMutex eventMutex;                        //!< Mutex held when firing events
    LockableConceptMutex commandMutex;                      //!< Mutex held while executing commands
    LockableConceptMutex varsMutex;                         //!< Mutex held when updating internal vars
    Semaphore terminateSem;                                 //!< Signaled when the background should shut down
    Semaphore wakeupSem;                                    //!< Signaled when the background should
    ThreadPtr backgroundThread;                             //!< Runs Background() function and implements scenario (nil when not initialized)
    Statistics stats;                                       //!< Current state of statistics
    Statistics mystats;                                     //!< Stats being manipulated (Background)
    bool isPowered;                                         //!< Power state of the modem (Background)
    CookieType messageCookie;                               //!< Cookie of the message that is about to be sent (Background)
    ByteArray messageData;                                  //!< Packet content of the message that is about to be sent (Background)
    SBDModem::Ptr modemPtr;                                 //!< Pointer to the modem instance (can be nil)
    SBDModem::ScopedConnectionPtr ringIndSubscription;		//!< Subscription to ring indicator event
    unsigned overrideMailboxCheckTime;                      //!< Used by Background to remember if the last message request wanted to override the next mailbox check
    bool havePosition;                                      //!< Determines if lat and lon settings are valid (true=valid)
    double savedLat;                                        //!< Saved latitude from SetPosition
    double savedLon;                                        //!< Saved longiude from SetPosition
    SBDModemSettings sbdModemSettings;                      //!< Settings in use back Background
    TimeCounter modemUpCounter;                             //!< Used by Background
    TimeCounter modemOffCounter;                            //!< Used by Background
    TimeCounter lastSessionCounter;                         //!< Used by Background
    TimeCounter errorCounter;                               //!< Used by Background
    TimeCounter networkUpCounter;                           //!< Used by Background
    ReceivedDataSignalType receivedDataSignal;              //!< Signals subscriber whenever a session reveals a packet received
    RequestDataToSendSignalType requestDataToSendSignal;    //!< Signals subscriber whenever a session is about to be executed to allow data to be sent
    SentDataSignalType sentDataSignal;                      //!< Signals subscriber whenever a session succeeds in sending a packet
    StatisticsSignalType statisticsSignal;                  //!< Signals subscriber whenever statistics change
};

}
}

#endif
