//----------------------------------------------------------------------------------------------
// <copyright file="LqrSMACSharedMemory.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 SharedMemory class, which wraps a Linux shared memory segment.  Methods
//	return true if successful, false on failure; most can be configured to throw an exception vs.
//	returning an error
// </summary>
//
// <owner>Mike Cookson</owner>
//----------------------------------------------------------------------------------------------

#ifndef __LqrSMACSharedMemory_H__
#define __LqrSMACSharedMemory_H__

#include "LqrSMACDeclareException.h"
#include "LqrSMACSharedLib.h"
#include <string>
#include <boost/thread/locks.hpp>
#include <boost/utility.hpp>
#include <semaphore.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <time.h>
#include <unistd.h>

namespace LiquidRobotics {
namespace SMACFramework {

class SHARED_LIB_PUBLIC SharedMemory : boost::noncopyable
{
public:

	typedef std::string string;
	typedef struct stat StatStruct;

	enum SHMOpenType
	{
		SHMO_CREATE = 0,				// create the file, but still open if it exists
		SHMO_CREATE_NEW = 1,			// create the file only if it does not exist
		SHMO_OPEN = 2,					// open the file (fails if it does not exist)

		SHMO_OPERATION_MASK = 3,

		SHMO_ANONYMOUS = 16,				// open as an anonymous segment (no file backing)
		SHMO_WRITEABLE = 32,			// add this flag to indicate the segment will be writeable
		SHMO_TRUNCATE = 64,				// add this flag to set the segment size to zero on open
	};

    class SHARED_LIB_PUBLIC SystemError : public std::runtime_error
    {
    public:
    	SystemError(const string& whatArg, int _errNum);
    	const int errNum;
    	inline string describe() const { return describe(errNum); }
    	static string describe(int errNum);
    };

    class SHARED_LIB_PUBLIC SystemCallInterrupted : public SystemError
    {
    public:
    	SystemCallInterrupted(const string& whatArg);
    };

	SharedMemory();
	SharedMemory(SHMOpenType _openType, int _fd, bool _keepLocked);
	SharedMemory(SHMOpenType _openType, const string& _segmentName, int createMode = 0600, bool _keepLocked = false);

	virtual ~SharedMemory();

	virtual bool ChMod(int newMode, bool throwOnFail = false);
	virtual bool ChOwn(uid_t newUID, gid_t newGID, bool throwOnFail = false);
	virtual void Close();
	virtual int GetFD() const;
	virtual off_t GetSize(bool throwOnFail = false) const;
	virtual bool IsMapped() const;
	virtual bool IsOpen() const;
	virtual void* Map(bool writeable = false, bool throwOnFail = false);
	virtual bool Open(SHMOpenType _openType, const string& _segmentName, int createMode = 0600, bool _keepLocked = false,
			bool throwOnFail = false);
	virtual void SetFD(SHMOpenType _openType, int _fd, bool _keepLocked);
	virtual bool SetSize(off_t newLength, bool throwOnFail = false);
	virtual bool Stat(int& st, StatStruct& statbuf, bool throwOnFail = false) const;
	virtual bool Unlink(bool throwOnFail = false);
	virtual bool Unmap(bool throwOnFail = false);

private:

	bool CheckOpen(bool throwOnFail, const string& msg);
	static bool CheckOpen2(int theFD, bool throwOnFail, const string& msg);
	static bool RunAPI(int theFD, int status, bool throwOnFail, const string& msg, unsigned lineNum);
	static void ThrowSystemError(bool throwOnFail, int errNum, const string& msg, unsigned lineNum);

	SHMOpenType openType;				// open operation type
	int fd;								// file descriptor representing the shared memory segment
	bool mapped;						// true if the segment is currently mapped, false if it is not mapped
	bool keepLocked;					// keep the memory segment locked in memory
	void* mapAddr;						// address that was mapped
	off_t mapLen;						// number of bytes mapped
};

}
}

#endif

