/*

   */

/***********************************************************************
 *   $Id: primproc.cpp 2147 2013-08-14 20:44:44Z bwilkinson $
 *
 *
 ***********************************************************************/
#include <unistd.h>
#include <string>
#include <iostream>
#ifdef QSIZE_DEBUG
#include <iomanip>
#include <fstream>
#endif
#include <csignal>
#include <sys/time.h>
#ifndef _MSC_VER
#include <sys/resource.h>
#include <tr1/unordered_set>
#else
#include <unordered_set>
#endif
#include <clocale>
#include <iterator>
#include <algorithm>
//#define NDEBUG
#include <cassert>
using namespace std;

#include <boost/thread.hpp>
#include <boost/regex.hpp>
#include <boost/tokenizer.hpp>
using namespace boost;

#include "configcpp.h"
using namespace config;

#include "messageids.h"
using namespace logging;

#include "primproc.h"
#include "primitiveserver.h"
#include "MonitorProcMem.h"
#include "pp_logger.h"
#include "umsocketselector.h"
using namespace primitiveprocessor;

#include "liboamcpp.h"
using namespace oam;

#include "utils_utf8.h"

#include "IDBPolicy.h"
using namespace idbdatafile;

#include "cgroupconfigurator.h"

namespace primitiveprocessor
{

extern uint32_t BPPCount;
extern uint32_t blocksReadAhead;
extern uint32_t defaultBufferSize;
extern uint32_t connectionsPerUM;
extern uint32_t highPriorityThreads;
extern uint32_t medPriorityThreads;
extern uint32_t lowPriorityThreads;
extern int  directIOFlag;
extern int  noVB;

DebugLevel gDebugLevel;
Logger* mlp;
string systemLang;
bool utf8 = false;

bool isDebug( const DebugLevel level )
{
	return level <= gDebugLevel;
}

}

namespace
{

int toInt(const string& val)
{
	if (val.length() == 0)
		return -1;
	return static_cast<int>(Config::fromText(val));
}

void setupSignalHandlers()
{
#ifndef _MSC_VER
	signal(SIGHUP, SIG_IGN);

	struct sigaction ign;

	memset(&ign, 0, sizeof(ign));
	ign.sa_handler = SIG_IGN;
	sigaction(SIGPIPE, &ign, 0);

	memset(&ign, 0, sizeof(ign));
	ign.sa_handler = SIG_IGN;
	sigaction(SIGUSR1, &ign, 0);

	memset(&ign, 0, sizeof(ign));
	ign.sa_handler = SIG_IGN;
	sigaction(SIGUSR2, &ign, 0);

	sigset_t sigset;
	sigemptyset(&sigset);
	sigaddset(&sigset, SIGPIPE);
	sigaddset(&sigset, SIGUSR1);
	sigaddset(&sigset, SIGUSR2);
	sigprocmask(SIG_BLOCK, &sigset, 0);

#endif
}

void setupCwd(Config* cf)
{
	string workdir = cf->getConfig("SystemConfig", "WorkingDir");
	if (workdir.length() == 0)
		workdir = ".";
	(void)chdir(workdir.c_str());
	if (access(".", W_OK) != 0)
		(void)chdir("/tmp");
}

int setupResources()
{
#ifndef _MSC_VER
	struct rlimit rlim;

	if (getrlimit(RLIMIT_NOFILE, &rlim) != 0) {
		return -1;
	}
	rlim.rlim_cur = rlim.rlim_max = 65536;
	if (setrlimit(RLIMIT_NOFILE, &rlim) != 0) {
		return -2;
	}

	if (getrlimit(RLIMIT_NOFILE, &rlim) != 0) {
		return -3;
	}

	if (rlim.rlim_cur != 65536) {
		return -4;
	}
#endif
	return 0;
}

#ifdef QSIZE_DEBUG
class QszMonThd
{
public:
	QszMonThd(PrimitiveServer* psp, ofstream* qszlog) : fPsp(psp), fQszLog(qszlog)
	{
	}

	~QszMonThd()
	{
	}

	void operator()()
	{
		for (;;)
		{
			uint32_t qd = fPsp->getProcessorThreadPool()->getWaiting();
			if (fQszLog)
			{
				// Get a timestamp for output.
				struct tm tm;
				struct timeval tv;

				gettimeofday(&tv, 0);
				localtime_r(&tv.tv_sec, &tm);

				ostringstream oss;
				oss << setfill('0')
				<< setw(2) << tm.tm_hour << ':'
				<< setw(2) << tm.tm_min << ':'
				<< setw(2) << tm.tm_sec
				<< '.'
				<< setw(4) << tv.tv_usec/100
				;

				*fQszLog << oss.str() << ' ' << qd << endl;
			}
			struct timespec req = { 0, 1000 * 100 }; //100 usec
			nanosleep(&req, 0);
		}
	}
private:
	//defaults okay
	const PrimitiveServer* fPsp;
	ofstream* fQszLog;
};
#endif

#ifndef _MSC_VER
#define DUMP_CACHE_CONTENTS
#endif
#ifdef DUMP_CACHE_CONTENTS
void* waitForSIGUSR1(void* p)
{
#if defined(__LP64__) || defined(_MSC_VER)
	ptrdiff_t tmp = reinterpret_cast<ptrdiff_t>(p);
	int cacheCount = static_cast<int>(tmp);
#else
	int cacheCount = reinterpret_cast<int>(p);
#endif
#ifndef _MSC_VER
	sigset_t oset;
	int rec_sig;
	int32_t rpt_state=0;
	sigfillset(&oset);
	sigdelset(&oset, SIGUSR1);
	sigdelset(&oset, SIGUSR2);
	pthread_sigmask(SIG_SETMASK, &oset, 0);

	sigemptyset(&oset);
	sigaddset(&oset, SIGUSR1);
	sigaddset(&oset, SIGUSR2);
#endif
	for (;;)
	{
		sigwait(&oset, &rec_sig);
		if (rec_sig == SIGUSR1)
		{
#ifdef _MSC_VER
			ofstream out("C:/Calpont/log/trace/pplru.dat");
#else
			ofstream out("/var/log/Calpont/trace/pplru.dat");
#endif
			for (int i = 0; i < cacheCount; i++)
			{
				BRPp[i]->formatLRUList(out);
				out << "###" << endl;
			}
		} else if (rec_sig == SIGUSR2)
		{
			// is reporting currently on?
			rpt_state = BRPp[0]->ReportingFrequency();
			if (rpt_state>0)
				rpt_state=0; // turn reporting off
			else
				rpt_state=1; // fbm will set to the value from config file

			for (int i = 0; i < cacheCount; i++)
				BRPp[i]->setReportingFrequency(rpt_state);
			cout << "@@@" << endl;
		}
	}
	return 0;
}
#endif

}

int main(int argc, char* argv[])
{
	// get and set locale language
	systemLang = funcexp::utf8::idb_setlocale();
	if ( systemLang != "en_US.UTF-8" &&
			systemLang.find("UTF") != string::npos )
		utf8 = true;

	Config* cf = Config::makeConfig();

	setupSignalHandlers();

	setupCwd(cf);

	mlp = new primitiveprocessor::Logger();

	int rc;
	rc = setupResources();
	if (rc) {
		Message::Args args;
		args.add(rc);
	}

	int serverThreads = 1;
	int serverQueueSize = 10;
	int processorWeight = 8*1024;
	int processorQueueSize = 10*1024;
	int BRPBlocksPct = 70;
	uint32_t BRPBlocks = 1887437;
	int BRPThreads = 16;
	int cacheCount = 1;
	int maxBlocksPerRead = 256;  // 1MB
	bool rotatingDestination = false;
	uint32_t deleteBlocks = 128;
	bool PTTrace = false;
	int temp;
	string strTemp;
	int priority = -1;
	const string primitiveServers("PrimitiveServers");
	const string jobListStr("JobList");
	const string dbbc("DBBC");
	const string ExtentMapStr("ExtentMap");
	uint64_t extentRows = 8*1024*1024;
	uint64_t MaxExtentSize = 0;
	double prefetchThreshold;
	uint64_t PMSmallSide = 67108864;
	BPPCount = 16;
	int numCores = -1;
	int configNumCores = -1;
	uint32_t highPriorityPercentage, medPriorityPercentage, lowPriorityPercentage;
	utils::CGroupConfigurator cg;

	gDebugLevel = primitiveprocessor::NONE;

	temp = toInt(cf->getConfig(primitiveServers, "ServerThreads"));
	if (temp > 0)
		serverThreads = temp;

	temp = toInt(cf->getConfig(primitiveServers, "ServerQueueSize"));
	if (temp > 0)
		serverQueueSize = temp;

	temp = toInt(cf->getConfig(primitiveServers, "ProcessorThreshold"));
	if (temp > 0)
		processorWeight = temp;

	temp = toInt(cf->getConfig(primitiveServers, "ProcessorQueueSize"));
	if (temp > 0)
		processorQueueSize = temp;

	temp = toInt(cf->getConfig(primitiveServers, "DebugLevel"));
	if (temp > 0)
		gDebugLevel = (DebugLevel)temp;

	highPriorityPercentage = 0;
	temp = toInt(cf->getConfig(primitiveServers, "HighPriorityPercentage"));
	if (temp >= 0)
		highPriorityPercentage = temp;

	medPriorityPercentage = 0;
	temp = toInt(cf->getConfig(primitiveServers, "MediumPriorityPercentage"));
	if (temp >= 0)
		medPriorityPercentage = temp;

	lowPriorityPercentage = 0;
	temp = toInt(cf->getConfig(primitiveServers, "LowPriorityPercentage"));
	if (temp >= 0)
		lowPriorityPercentage = temp;

	temp = toInt(cf->getConfig(ExtentMapStr, "ExtentRows"));
	if (temp > 0)
		extentRows = temp;

	temp = toInt(cf->getConfig(primitiveServers, "ConnectionsPerPrimProc"));
	if (temp > 0)
		connectionsPerUM = temp;
	else
		connectionsPerUM = 1;

	// set to smallest extent size
	// do not allow to read beyond the end of an extent
	const int MaxReadAheadSz = (extentRows)/BLOCK_SIZE;
	//defaultBufferSize = 512 * 1024; // @bug 2627 - changed default dict buffer from 256K to 512K, allows for cols w/ length of 61.
	defaultBufferSize = 100*1024;  // 1/17/12 - made the dict buffer dynamic, max size for a numeric col is 80k + ovrhd

	// This parm controls whether we rotate through the output sockets
	// when deciding where to send response messages, or whether to simply
	// send the response to the socket of origin.  Should normally be set
	string strVal = cf->getConfig(primitiveServers, "RotatingDestination");
	strVal = "N";
	if ((strVal == "y") || (strVal == "Y")) {
		rotatingDestination = true;

		// Disable destination rotation if UM and PM are running on same
		// server, because we could accidentally end up sending DMLProc
		// responses to ExeMgr and vice versa, if we rotated socket dest.
		temp = toInt(cf->getConfig("Installation", "ServerTypeInstall"));
		if ((temp == oam::INSTALL_COMBINE_DM_UM_PM) ||
				(temp == oam::INSTALL_COMBINE_PM_UM))
			rotatingDestination = false;
	}

	string strBlockPct = cf->getConfig(dbbc, "NumBlocksPct");
	temp = atoi(strBlockPct.c_str());
	if (temp > 0)
		BRPBlocksPct = temp;

#ifdef _MSC_VER
	MEMORYSTATUSEX memStat;
	memStat.dwLength = sizeof(memStat);
	if (GlobalMemoryStatusEx(&memStat) == 0)
		BRPBlocks = 2621 * BRPBlocksPct;
	else
	{
#ifndef _WIN64
		memStat.ullTotalPhys = std::min(memStat.ullTotalVirtual, memStat.ullTotalPhys);
#endif
		//We now have the total phys mem in bytes

BRPBlocks = memStat.ullTotalPhys / (8 * 1024) / 100 * BRPBlocksPct;
	}
#else
	// _SC_PHYS_PAGES is in 4KB units. Dividing by 200 converts to 8KB and gets ready to work in pct
	// _SC_PHYS_PAGES should always be >> 200 so we shouldn't see a total loss of precision
	BRPBlocks = ((BRPBlocksPct/100.0) * (double) cg.getTotalMemory()) / 8192;
#endif
#if 0
	temp = toInt(cf->getConfig(dbbc, "NumThreads"));
	if (temp > 0)
		BRPThreads = temp;
#endif
	temp = toInt(cf->getConfig(dbbc, "NumCaches"));
	if (temp > 0)
		cacheCount = temp;

	temp = toInt(cf->getConfig(dbbc, "NumDeleteBlocks"));
	if (temp > 0)
		deleteBlocks = temp;

	if ((uint32_t)(.01 * BRPBlocks) < deleteBlocks)
		deleteBlocks = (uint32_t)(.01 * BRPBlocks);

	temp = toInt(cf->getConfig(primitiveServers, "ColScanBufferSizeBlocks"));
	if (temp > (int) MaxReadAheadSz || temp < 1)
		maxBlocksPerRead = MaxReadAheadSz;
	else if (temp > 0)
		maxBlocksPerRead = temp;

	temp = toInt(cf->getConfig(primitiveServers, "ColScanReadAheadBlocks"));
	if (temp > (int) MaxReadAheadSz || temp < 0)
		blocksReadAhead = MaxReadAheadSz;
	else if (temp > 0)
	{
		//make sure we've got an integral factor of extent size
		for (; (MaxExtentSize%temp)!=0; ++temp);
		blocksReadAhead=temp;
	}

	temp = toInt(cf->getConfig(primitiveServers, "PTTrace"));
	if (temp > 0)
		PTTrace = true;

	temp = toInt(cf->getConfig(primitiveServers, "PrefetchThreshold"));
	if (temp < 0 || temp > 100)
		prefetchThreshold = 0;
	else
		prefetchThreshold = temp/100.0;

	int maxPct = 0; //disable by default
	temp = toInt(cf->getConfig(primitiveServers, "MaxPct"));
	if (temp >= 0)
		maxPct = temp;

	// @bug4507, configurable pm aggregation AggregationMemoryCheck
	// We could use this same mechanism for other growing buffers.
	int aggPct = 95;
	temp = toInt(cf->getConfig("SystemConfig", "MemoryCheckPercent"));
	if (temp >= 0)
		aggPct = temp;

	//...Start the thread to monitor our memory usage
	new boost::thread(utils::MonitorProcMem(maxPct, aggPct, 28));

	// config file priority is 40..1 (highest..lowest)
	string sPriority = cf->getConfig(primitiveServers, "Priority");
	if (sPriority.length() > 0)
		temp = toInt(sPriority);
	else
		temp = 21;

	// convert config file value to setpriority(2) value (-20..19, -1 is the default)
	if (temp > 0)
		priority = 20 - temp;
	else if (temp < 0)
		priority = 19;

	if (priority < -20) priority = -20;
#ifdef _MSC_VER
#else
	setpriority(PRIO_PROCESS, 0, priority);
#endif
	//..Instantiate UmSocketSelector singleton.  Disable rotating destination
	//..selection if no UM IP addresses are in the Calpo67108864LLnt.xml file.
	UmSocketSelector* pUmSocketSelector = UmSocketSelector::instance();
	if (rotatingDestination)
	{
		if (pUmSocketSelector->ipAddressCount() < 1)
			rotatingDestination = false;
	}

	//See if we want to override the calculated #cores
	temp = toInt(cf->getConfig(primitiveServers, "NumCores"));
	if (temp > 0)
		configNumCores = temp;

	if (configNumCores <= 0)
	{
		//count the actual #cores

		numCores = cg.getNumCores();
		if (numCores == 0)
			numCores = 8;
	}
	else
		numCores = configNumCores;

	//based on the #cores, calculate some thread parms
	if (numCores > 0)
	{
		BRPThreads = 2 * numCores;
		//there doesn't seem much benefit to having more than this, and sometimes it causes problems.
		//DBBC.NumThreads can override this cap
		BRPThreads = std::min(BRPThreads, 32);
	}

	if (highPriorityPercentage == 0 && medPriorityPercentage == 0 &&
			lowPriorityPercentage == 0) {
		lowPriorityThreads = max(1, (2*numCores)/10);
		medPriorityThreads = max(1, (2*numCores)/3);
		highPriorityThreads = (2 * numCores) - lowPriorityThreads - medPriorityThreads;
	}
	else {
		uint32_t totalThreads = (uint32_t) ((lowPriorityPercentage + medPriorityPercentage +
											 highPriorityPercentage) / 100.0 * (2*numCores));

		if (totalThreads == 0)
			totalThreads = 1;

		lowPriorityThreads = (uint32_t) (lowPriorityPercentage/100.0 * (2*numCores));
		medPriorityThreads = (uint32_t) (medPriorityPercentage/100.0 * (2*numCores));
		highPriorityThreads = totalThreads - lowPriorityThreads - medPriorityThreads;
	}

	BPPCount = highPriorityThreads + medPriorityThreads + lowPriorityThreads;

	// let the user override if they want
	temp = toInt(cf->getConfig(primitiveServers, "BPPCount"));
	if (temp > 0 && temp < (int) BPPCount)
		BPPCount = temp;

	temp = toInt(cf->getConfig(dbbc, "NumThreads"));
	if (temp > 0)
		BRPThreads = temp;

#ifndef _MSC_VER
	// @bug4598, switch for O_DIRECT to support gluster fs.
	strVal = cf->getConfig(primitiveServers, "DirectIO");
	if ((strVal == "n") || (strVal == "N"))
		directIOFlag = 0;
#endif

	IDBPolicy::configIDBPolicy();

	// no versionbuffer if using HDFS for performance reason
	if (IDBPolicy::useHdfs())
		noVB = 1;

	cout << "Starting PrimitiveServer: st = " << serverThreads << ", sq = " << serverQueueSize <<
		 ", pw = " << processorWeight << ", pq = " << processorQueueSize <<
		 ", nb = " << BRPBlocks << ", nt = " << BRPThreads << ", nc = " << cacheCount <<
		 ", ra = " << blocksReadAhead <<  ", db = " << deleteBlocks << ", mb = " << maxBlocksPerRead <<
		 ", rd = " << rotatingDestination << ", tr = " << PTTrace <<
		 ", ss = " << PMSmallSide << ", bp = " << BPPCount << endl;

	PrimitiveServer server(serverThreads, serverQueueSize, processorWeight, processorQueueSize,
						   rotatingDestination, BRPBlocks, BRPThreads, cacheCount, maxBlocksPerRead, blocksReadAhead,
						   deleteBlocks, PTTrace, prefetchThreshold, PMSmallSide);

#ifdef QSIZE_DEBUG
	thread* qszMonThd;
	if (gDebugLevel >= STATS)
	{
#ifdef _MSC_VER
		ofstream* qszLog = new ofstream("C:/Calpont/log/trace/ppqsz.dat");
#else
		ofstream* qszLog = new ofstream("/var/log/Calpont/trace/ppqsz.dat");
#endif
		if (!qszLog->good())
		{
			qszLog->close();
			delete qszLog;
			qszLog = 0;
		}
		qszMonThd = new thread(QszMonThd(&server, qszLog));
	}
#endif

#ifdef DUMP_CACHE_CONTENTS
	{
		//Need to use pthreads API here...
		pthread_t thd1;
		pthread_attr_t attr1;
		pthread_attr_init(&attr1);
		pthread_attr_setdetachstate(&attr1, PTHREAD_CREATE_DETACHED);
		pthread_create(&thd1, &attr1, waitForSIGUSR1, reinterpret_cast<void*>(cacheCount));
	}
#endif

	server.start();

	cerr << "server.start() exited!" << endl;

	return 1;
}


#include "msgpack.hpp"

#include <cmath>
#include <string>
#include <vector>
#include <map>
#include <deque>
#include <set>
#include <list>
#include <limits>

#include <gtest/gtest.h>

#ifdef HAVE_CONFIG_H
#include "config.h"
#endif

using namespace std;

#define GEN_TEST_VREF(test_type, vbuf)                                  \
  do {                                                                  \
    vector<test_type> v;                                                \
    v.push_back(0);                                                     \
    for (unsigned int i = 0; i < v.size(); i++) {                       \
      test_type val1 = v[i];                                            \
      msgpack::pack(vbuf, val1);                                        \
      msgpack::sbuffer sbuf;                                            \
      const struct iovec* cur = vbuf.vector();                          \
      const struct iovec* end = cur + vbuf.vector_size();               \
      for(; cur != end; ++cur)                                          \
        sbuf.write((const char*)cur->iov_base, cur->iov_len);           \
      msgpack::unpacked ret;                                            \
      msgpack::unpack(ret, sbuf.data(), sbuf.size());                   \
      test_type val2 = ret.get().as<test_type>();                       \
      EXPECT_EQ(val1, val2);                                            \
    }                                                                   \
  } while(0);

TEST(MSGPACK, vrefbuffer_char)
{
  msgpack::vrefbuffer vbuf;
  GEN_TEST_VREF(char, vbuf);
}

TEST(MSGPACK, vrefbuffer_signed_char)
{
  msgpack::vrefbuffer vbuf;
  GEN_TEST_VREF(signed char, vbuf);
}

TEST(MSGPACK, vrefbuffer_unsigned_char)
{
  msgpack::vrefbuffer vbuf;
  GEN_TEST_VREF(unsigned char, vbuf);
}

TEST(MSGPACK, vrefbuffer_short)
{
  msgpack::vrefbuffer vbuf;
  GEN_TEST_VREF(short, vbuf);
}

TEST(MSGPACK, vrefbuffer_int)
{
  msgpack::vrefbuffer vbuf;
  GEN_TEST_VREF(int, vbuf);
}

TEST(MSGPACK, vrefbuffer_long)
{
  msgpack::vrefbuffer vbuf;
  GEN_TEST_VREF(long, vbuf);
}

TEST(MSGPACK, vrefbuffer_long_long)
{
  msgpack::vrefbuffer vbuf;
  GEN_TEST_VREF(long long, vbuf);
}

TEST(MSGPACK, vrefbuffer_unsigned_short)
{
  msgpack::vrefbuffer vbuf;
  GEN_TEST_VREF(unsigned short, vbuf);
}

TEST(MSGPACK, vrefbuffer_unsigned_int)
{
  msgpack::vrefbuffer vbuf;
  GEN_TEST_VREF(unsigned int, vbuf);
}

TEST(MSGPACK, vrefbuffer_unsigned_long)
{
  msgpack::vrefbuffer vbuf;
  GEN_TEST_VREF(unsigned long, vbuf);
}

TEST(MSGPACK, vrefbuffer_unsigned_long_long)
{
  msgpack::vrefbuffer vbuf;
  GEN_TEST_VREF(unsigned long long, vbuf);
}

TEST(MSGPACK, vrefbuffer_uint8)
{
  msgpack::vrefbuffer vbuf;
  GEN_TEST_VREF(uint8_t, vbuf);
}

TEST(MSGPACK, vrefbuffer_uint16)
{
  msgpack::vrefbuffer vbuf;
  GEN_TEST_VREF(uint16_t, vbuf);
}

TEST(MSGPACK, vrefbuffer_uint32)
{
  msgpack::vrefbuffer vbuf;
  GEN_TEST_VREF(uint32_t, vbuf);
}

TEST(MSGPACK, vrefbuffer_uint64)
{
  msgpack::vrefbuffer vbuf;
  GEN_TEST_VREF(uint64_t, vbuf);
}

TEST(MSGPACK, vrefbuffer_int8)
{
  msgpack::vrefbuffer vbuf;
  GEN_TEST_VREF(int8_t, vbuf);
}

TEST(MSGPACK, vrefbuffer_int16)
{
  msgpack::vrefbuffer vbuf;
  GEN_TEST_VREF(int16_t, vbuf);
}

TEST(MSGPACK, vrefbuffer_int32)
{
  msgpack::vrefbuffer vbuf;
  GEN_TEST_VREF(int32_t, vbuf);
}

TEST(MSGPACK, vrefbuffer_int64)
{
  msgpack::vrefbuffer vbuf;
  GEN_TEST_VREF(int64_t, vbuf);
}

// small ref_size and chunk_size
TEST(MSGPACK, vrefbuffer_small_char)
{
  msgpack::vrefbuffer vbuf(0, 0);
  GEN_TEST_VREF(char, vbuf);
}

TEST(MSGPACK, vrefbuffer_small_signed_char)
{
  msgpack::vrefbuffer vbuf(0, 0);
  GEN_TEST_VREF(signed char, vbuf);
}

{
  msgpack::vrefbuffer vbuf(0, 0);
  GEN_TEST_VREF(unsigned char, vbuf);
}

TEST(MSGPACK, vrefbuffer_small_short)
{
  msgpack::vrefbuffer vbuf(0, 0);
  GEN_TEST_VREF(short, vbuf);
}

TEST(MSGPACK, vrefbuffer_small_int)
{
  msgpack::vrefbuffer vbuf(0, 0);
  GEN_TEST_VREF(int, vbuf);
}

TEST(MSGPACK, vrefbuffer_small_long)
{
  msgpack::vrefbuffer vbuf(0, 0);
  GEN_TEST_VREF(long, vbuf);
}

TEST(MSGPACK, vrefbuffer_small_long_long)
{
  msgpack::vrefbuffer vbuf(0, 0);
  GEN_TEST_VREF(long long, vbuf);
}

TEST(MSGPACK, vrefbuffer_small_unsigned_short)
{
  msgpack::vrefbuffer vbuf(0, 0);
  GEN_TEST_VREF(unsigned short, vbuf);
}

TEST(MSGPACK, vrefbuffer_small_unsigned_int)
{
  msgpack::vrefbuffer vbuf(0, 0);
  GEN_TEST_VREF(unsigned int, vbuf);
}

TEST(MSGPACK, vrefbuffer_small_unsigned_long)
{
  msgpack::vrefbuffer vbuf(0, 0);
  GEN_TEST_VREF(unsigned long, vbuf);
}

TEST(MSGPACK, vrefbuffer_small_unsigned_long_long)
{
  msgpack::vrefbuffer vbuf(0, 0);
  GEN_TEST_VREF(unsigned long long, vbuf);
}

TEST(MSGPACK, vrefbuffer_small_uint8)
{
  msgpack::vrefbuffer vbuf(0, 0);
  GEN_TEST_VREF(uint8_t, vbuf);
}

TEST(MSGPACK, vrefbuffer_small_uint16)
{
  msgpack::vrefbuffer vbuf(0, 0);
  GEN_TEST_VREF(uint16_t, vbuf);
}

TEST(MSGPACK, vrefbuffer_small_uint32)
{
  msgpack::vrefbuffer vbuf(0, 0);
  GEN_TEST_VREF(uint32_t, vbuf);
}

TEST(MSGPACK, vrefbuffer_small_uint64)
{
  msgpack::vrefbuffer vbuf(0, 0);
  GEN_TEST_VREF(uint64_t, vbuf);
}

TEST(MSGPACK, vrefbuffer_small_int8)
{
  msgpack::vrefbuffer vbuf(0, 0);
  GEN_TEST_VREF(int8_t, vbuf);
}

TEST(MSGPACK, vrefbuffer_small_int16)
{
  msgpack::vrefbuffer vbuf(0, 0);
  GEN_TEST_VREF(int16_t, vbuf);
}

TEST(MSGPACK, vrefbuffer_small_int32)
{
  msgpack::vrefbuffer vbuf(0, 0);
  GEN_TEST_VREF(int32_t, vbuf);
}

TEST(MSGPACK, vrefbuffer_small_int64)
{
  msgpack::vrefbuffer vbuf(0, 0);
  GEN_TEST_VREF(int64_t, vbuf);
}


{
  msgpack::vrefbuffer vbuf(0, 0);
  GEN_TEST_VREF(unsigned long, vbuf);
}

#include "msgpack.hpp"

#include <cmath>
#include <string>
#include <vector>
#include <map>
#include <deque>
#include <set>
#include <list>
#include <limits>

#include <gtest/gtest.h>

#ifdef HAVE_CONFIG_H
#include "config.h"
#endif

using namespace std;

#define GEN_TEST_VREF(test_type, vbuf)                                  \
  do {                                                                  \
    vector<test_type> v;                                                \
    v.push_back(0);                                                     \
    for (unsigned int i = 0; i < v.size(); i++) {                       \
      test_type val1 = v[i];                                            \
      msgpack::pack(vbuf, val1);                                        \
      msgpack::sbuffer sbuf;                                            \
      const struct iovec* cur = vbuf.vector();                          \
      const struct iovec* end = cur + vbuf.vector_size();               \
      for(; cur != end; ++cur)                                          \
        sbuf.write((const char*)cur->iov_base, cur->iov_len);           \
      msgpack::unpacked ret;                                            \
      msgpack::unpack(ret, sbuf.data(), sbuf.size());                   \
      test_type val2 = ret.get().as<test_type>();                       \
      EXPECT_EQ(val1, val2);                                            \
    }                                                                   \
  } while(0);

TEST(MSGPACK, vrefbuffer_char)
{
  msgpack::vrefbuffer vbuf;
  GEN_TEST_VREF(char, vbuf);
}

TEST(MSGPACK, vrefbuffer_signed_char)
{
  msgpack::vrefbuffer vbuf;
  GEN_TEST_VREF(signed char, vbuf);
}

TEST(MSGPACK, vrefbuffer_unsigned_char)
{
  msgpack::vrefbuffer vbuf;
  GEN_TEST_VREF(unsigned char, vbuf);
}

TEST(MSGPACK, vrefbuffer_short)
{
  msgpack::vrefbuffer vbuf;
  GEN_TEST_VREF(short, vbuf);
}

TEST(MSGPACK, vrefbuffer_int)
{
  msgpack::vrefbuffer vbuf;
  GEN_TEST_VREF(int, vbuf);
}

TEST(MSGPACK, vrefbuffer_long)
{
  msgpack::vrefbuffer vbuf;
  GEN_TEST_VREF(long, vbuf);
}

TEST(MSGPACK, vrefbuffer_long_long)
{
  msgpack::vrefbuffer vbuf;
  GEN_TEST_VREF(long long, vbuf);
}

TEST(MSGPACK, vrefbuffer_unsigned_short)
{
  msgpack::vrefbuffer vbuf;
  GEN_TEST_VREF(unsigned short, vbuf);
}

TEST(MSGPACK, vrefbuffer_unsigned_int)
{
  msgpack::vrefbuffer vbuf;
  GEN_TEST_VREF(unsigned int, vbuf);
}

TEST(MSGPACK, vrefbuffer_unsigned_long)
{
  msgpack::vrefbuffer vbuf;
  GEN_TEST_VREF(unsigned long, vbuf);
}

TEST(MSGPACK, vrefbuffer_unsigned_long_long)
{
  msgpack::vrefbuffer vbuf;
  GEN_TEST_VREF(unsigned long long, vbuf);
}

TEST(MSGPACK, vrefbuffer_uint8)
{
  msgpack::vrefbuffer vbuf;
  GEN_TEST_VREF(uint8_t, vbuf);
}

TEST(MSGPACK, vrefbuffer_uint16)
{
  msgpack::vrefbuffer vbuf;
  GEN_TEST_VREF(uint16_t, vbuf);
}

TEST(MSGPACK, vrefbuffer_uint32)
{
  msgpack::vrefbuffer vbuf;
  GEN_TEST_VREF(uint32_t, vbuf);
}

TEST(MSGPACK, vrefbuffer_uint64)
{
  msgpack::vrefbuffer vbuf;
  GEN_TEST_VREF(uint64_t, vbuf);
}

TEST(MSGPACK, vrefbuffer_int8)
{
  msgpack::vrefbuffer vbuf;
  GEN_TEST_VREF(int8_t, vbuf);
}

TEST(MSGPACK, vrefbuffer_int16)
{
  msgpack::vrefbuffer vbuf;
  GEN_TEST_VREF(int16_t, vbuf);
}

TEST(MSGPACK, vrefbuffer_int32)
{
  msgpack::vrefbuffer vbuf;
  GEN_TEST_VREF(int32_t, vbuf);
}

TEST(MSGPACK, vrefbuffer_int64)
{
  msgpack::vrefbuffer vbuf;
  GEN_TEST_VREF(int64_t, vbuf);
}

// small ref_size and chunk_size
TEST(MSGPACK, vrefbuffer_small_char)
{
  msgpack::vrefbuffer vbuf(0, 0);
  GEN_TEST_VREF(char, vbuf);
}

TEST(MSGPACK, vrefbuffer_small_signed_char)
{
  msgpack::vrefbuffer vbuf(0, 0);
  GEN_TEST_VREF(signed char, vbuf);
}

TEST(MSGPACK, vrefbuffer_small_unsigned_char)
{
  msgpack::vrefbuffer vbuf(0, 0);
  GEN_TEST_VREF(unsigned char, vbuf);
}

TEST(MSGPACK, vrefbuffer_small_short)
{
  msgpack::vrefbuffer vbuf(0, 0);
  GEN_TEST_VREF(short, vbuf);
}

TEST(MSGPACK, vrefbuffer_small_int)
{
  msgpack::vrefbuffer vbuf(0, 0);
  GEN_TEST_VREF(int, vbuf);
}

TEST(MSGPACK, vrefbuffer_small_long)
{
  msgpack::vrefbuffer vbuf(0, 0);
  GEN_TEST_VREF(long, vbuf);
}

TEST(MSGPACK, vrefbuffer_small_long_long)
{
  msgpack::vrefbuffer vbuf(0, 0);
  GEN_TEST_VREF(long long, vbuf);
}

TEST(MSGPACK, vrefbuffer_small_unsigned_short)
{
  msgpack::vrefbuffer vbuf(0, 0);
  GEN_TEST_VREF(unsigned short, vbuf);
}

TEST(MSGPACK, vrefbuffer_small_unsigned_int)
{
  msgpack::vrefbuffer vbuf(0, 0);
  GEN_TEST_VREF(unsigned int, vbuf);
}

TEST(MSGPACK, vrefbuffer_small_unsigned_long)

TEST(MSGPACK, vrefbuffer_small_unsigned_long_long)
{
  msgpack::vrefbuffer vbuf(0, 0);
  GEN_TEST_VREF(unsigned long long, vbuf);
}

TEST(MSGPACK, vrefbuffer_small_uint8)
{
  msgpack::vrefbuffer vbuf(0, 0);
  GEN_TEST_VREF(uint8_t, vbuf);
}

TEST(MSGPACK, vrefbuffer_small_uint16)
{
  msgpack::vrefbuffer vbuf(0, 0);
  GEN_TEST_VREF(uint16_t, vbuf);
}

TEST(MSGPACK, vrefbuffer_small_uint32)
{
  msgpack::vrefbuffer vbuf(0, 0);
  GEN_TEST_VREF(uint32_t, vbuf);
}

TEST(MSGPACK, vrefbuffer_small_uint64)
{
  msgpack::vrefbuffer vbuf(0, 0);
  GEN_TEST_VREF(uint64_t, vbuf);
}

TEST(MSGPACK, vrefbuffer_small_int8)
{
  msgpack::vrefbuffer vbuf(0, 0);
  GEN_TEST_VREF(int8_t, vbuf);
}

TEST(MSGPACK, vrefbuffer_small_int16)
{
  msgpack::vrefbuffer vbuf(0, 0);
  GEN_TEST_VREF(int16_t, vbuf);
}

TEST(MSGPACK, vrefbuffer_small_int32)
{
  msgpack::vrefbuffer vbuf(0, 0);
  GEN_TEST_VREF(int32_t, vbuf);
}

TEST(MSGPACK, vrefbuffer_small_int64)
{
  msgpack::vrefbuffer vbuf(0, 0);
  GEN_TEST_VREF(int64_t, vbuf);
}


#include "msgpack.hpp"

#include <cmath>
#include <string>
#include <vector>
#include <map>
#include <deque>
#include <set>
#include <list>
#include <limits>

#include <gtest/gtest.h>

#ifdef HAVE_CONFIG_H
#include "config.h"
#endif

using namespace std;

#define GEN_TEST_VREF(test_type, vbuf)                                  \
  do {                                                                  \
    vector<test_type> v;                                                \
    v.push_back(0);                                                     \
    for (unsigned int i = 0; i < v.size(); i++) {                       \
      test_type val1 = v[i];                                            \
      msgpack::pack(vbuf, val1);                                        \
      msgpack::sbuffer sbuf;                                            \
      const struct iovec* cur = vbuf.vector();                          \
      const struct iovec* end = cur + vbuf.vector_size();               \
      for(; cur != end; ++cur)                                          \
        sbuf.write((const char*)cur->iov_base, cur->iov_len);           \
      msgpack::unpacked ret;                                            \
      msgpack::unpack(ret, sbuf.data(), sbuf.size());                   \
      test_type val2 = ret.get().as<test_type>();                       \
      EXPECT_EQ(val1, val2);                                            \
    }                                                                   \
  } while(0);

TEST(MSGPACK, vrefbuffer_char)
{
  msgpack::vrefbuffer vbuf;
  GEN_TEST_VREF(char, vbuf);
}

TEST(MSGPACK, vrefbuffer_signed_char)
{
  msgpack::vrefbuffer vbuf;
  GEN_TEST_VREF(signed char, vbuf);
}

TEST(MSGPACK, vrefbuffer_unsigned_char)
{
  msgpack::vrefbuffer vbuf;
  GEN_TEST_VREF(unsigned char, vbuf);
}

TEST(MSGPACK, vrefbuffer_short)
{
  msgpack::vrefbuffer vbuf;
  GEN_TEST_VREF(short, vbuf);
}

TEST(MSGPACK, vrefbuffer_int)
{
  msgpack::vrefbuffer vbuf;
  GEN_TEST_VREF(int, vbuf);
}

TEST(MSGPACK, vrefbuffer_long)
{
  msgpack::vrefbuffer vbuf;
  GEN_TEST_VREF(long, vbuf);
}

TEST(MSGPACK, vrefbuffer_long_long)
{
  msgpack::vrefbuffer vbuf;
  GEN_TEST_VREF(long long, vbuf);
}

TEST(MSGPACK, vrefbuffer_unsigned_short)
{
  msgpack::vrefbuffer vbuf;
  GEN_TEST_VREF(unsigned short, vbuf);
}

TEST(MSGPACK, vrefbuffer_unsigned_int)
{
  msgpack::vrefbuff

  GEN_TEST_VREF(unsigned int, vbuf);
}

TEST(MSGPACK, vrefbuffer_unsigned_long)
{
  msgpack::vrefbuffer vbuf;
  GEN_TEST_VREF(unsigned long, vbuf);
}

TEST(MSGPACK, vrefbuffer_unsigned_long_long)
{
  msgpack::vrefbuffer vbuf;
  GEN_TEST_VREF(unsigned long long, vbuf);
}

TEST(MSGPACK, vrefbuffer_uint8)
{
  msgpack::vrefbuffer vbuf;
  GEN_TEST_VREF(uint8_t, vbuf);
}

TEST(MSGPACK, vrefbuffer_uint16)
{
  msgpack::vrefbuffer vbuf;
  GEN_TEST_VREF(uint16_t, vbuf);
}

TEST(MSGPACK, vrefbuffer_uint32)
{
  msgpack::vrefbuffer vbuf;
  GEN_TEST_VREF(uint32_t, vbuf);
}

TEST(MSGPACK, vrefbuffer_uint64)
{
  msgpack::vrefbuffer vbuf;
  GEN_TEST_VREF(uint64_t, vbuf);
}

TEST(MSGPACK, vrefbuffer_int8)
{
  msgpack::vrefbuffer vbuf;
  GEN_TEST_VREF(int8_t, vbuf);
}

TEST(MSGPACK, vrefbuffer_int16)
{
  msgpack::vrefbuffer vbuf;
  GEN_TEST_VREF(int16_t, vbuf);
}

TEST(MSGPACK, vrefbuffer_int32)
{
  msgpack::vrefbuffer vbuf;
  GEN_TEST_VREF(int32_t, vbuf);
}

TEST(MSGPACK, vrefbuffer_int64)
{
  msgpack::vrefbuffer vbuf;
  GEN_TEST_VREF(int64_t, vbuf);
}

// small ref_size and chunk_size
TEST(MSGPACK, vrefbuffer_small_char)
{
  msgpack::vrefbuffer vbuf(0, 0);
  GEN_TEST_VREF(char, vbuf);
}

TEST(MSGPACK, vrefbuffer_small_signed_char)
{
  msgpack::vrefbuffer vbuf(0, 0);
  GEN_TEST_VREF(signed char, vbuf);
}

TEST(MSGPACK, vrefbuffer_small_unsigned_char)
{
  msgpack::vrefbuffer vbuf(0, 0);
  GEN_TEST_VREF(unsigned char, vbuf);
}

TEST(MSGPACK, vrefbuffer_small_short)
{
  msgpack::vrefbuffer vbuf(0, 0);
  GEN_TEST_VREF(short, vbuf);
}

TEST(MSGPACK, vrefbuffer_small_int)
{
  msgpack::vrefbuffer vbuf(0, 0);
  GEN_TEST_VREF(int, vbuf);
}

TEST(MSGPACK, vrefbuffer_small_long)
{
  msgpack::vrefbuffer vbuf(0, 0);
  GEN_TEST_VREF(long, vbuf);
}

TEST(MSGPACK, vrefbuffer_small_long_long)
{
  msgpack::vrefbuffer vbuf(0, 0);
  GEN_TEST_VREF(long long, vbuf);
}

TEST(MSGPACK, vrefbuffer_small_unsigned_short)
{
  msgpack::vrefbuffer vbuf(0, 0);
  GEN_TEST_VREF(unsigned short, vbuf);
}

TEST(MSGPACK, vrefbuffer_small_unsigned_int)
{
  msgpack::vrefbuffer vbuf(0, 0);
  GEN_TEST_VREF(unsigned int, vbuf);
}

TEST(MSGPACK, vrefbuffer_small_unsigned_long)
{
  msgpack::vrefbuffer vbuf(0, 0);
  GEN_TEST_VREF(unsigned long, vbuf);
}

TEST(MSGPACK, vrefbuffer_small_unsigned_long_long)
{
  msgpack::vrefbuffer vbuf(0, 0);
  GEN_TEST_VREF(unsigned long long, vbuf);
}

TEST(MSGPACK, vrefbuffer_small_uint8)
{
  msgpack::vrefbuffer vbuf(0, 0);
  GEN_TEST_VREF(uint8_t, vbuf);
}

TEST(MSGPACK, vrefbuffer_small_uint16)
{
  msgpack::vrefbuffer vbuf(0, 0);
  GEN_TEST_VREF(uint16_t, vbuf);
}

TEST(MSGPACK, vrefbuffer_small_uint32)
{
  msgpack::vrefbuffer vbuf(0, 0);
  GEN_TEST_VREF(uint32_t, vbuf);
}

TEST(MSGPACK, vrefbuffer_small_uint64)
{
  msgpack::vrefbuffer vbuf(0, 0);
  GEN_TEST_VREF(uint64_t, vbuf);
}

TEST(MSGPACK, vrefbuffer_small_int8)
{
  msgpack::vrefbuffer vbuf(0, 0);
  GEN_TEST_VREF(int8_t, vbuf);
}

TEST(MSGPACK, vrefbuffer_small_int16)
{
  msgpack::vrefbuffer vbuf(0, 0);
  GEN_TEST_VREF(int16_t, vbuf);
}

TEST(MSGPACK, vrefbuffer_small_int32)
{
  msgpack::vrefbuffer vbuf(0, 0);
  GEN_TEST_VREF(int32_t, vbuf);
}

TEST(MSGPACK, vrefbuffer_small_int64)
{
  msgpack::vrefbuffer vbuf(0, 0);
  GEN_TEST_VREF(int64_t, vbuf);
}


TEST(MSGPACK, vrefbuffer_small_char)
{
  msgpack::vrefbuffer vbuf(0, 0);
  GEN_TEST_VREF(char, vbuf);
}

#include "msgpack.hpp"

#include <cmath>
#include <string>
#include <vector>
#include <map>
#include <deque>
#include <set>
#include <list>
#include <limits>

#include <gtest/gtest.h>

#ifdef HAVE_CONFIG_H
#include "config.h"
#endif

using namespace std;

#define GEN_TEST_VREF(test_type, vbuf)                                  \
  do {                                                                  \
    vector<test_type> v;                                                \
    v.push_back(0);                                                     \
    for (unsigned int i = 0; i < v.size(); i++) {                       \
      test_type val1 = v[i];                                            \
      msgpack::pack(vbuf, val1);                                        \
      msgpack::sbuffer sbuf;                                            \
      const struct iovec* cur = vbuf.vector();                          \
      const struct iovec* end = cur + vbuf.vector_size();               \
      for(; cur != end; ++cur)                                          \
        sbuf.write((const char*)cur->iov_base, cur->iov_len);           \
      msgpack::unpacked ret;                                            \
      msgpack::unpack(ret, sbuf.data(), sbuf.size());                   \
      test_type val2 = ret.get().as<test_type>();                       \
      EXPECT_EQ(val1, val2);                                            \
    }                                                                   \
  } while(0);

TEST(MSGPACK, vrefbuffer_char)
{
  msgpack::vrefbuffer vbuf;
  GEN_TEST_VREF(char, vbuf);
}

TEST(MSGPACK, vrefbuffer_signed_char)
{
  msgpack::vrefbuffer vbuf;
  GEN_TEST_VREF(signed char, vbuf);
}

TEST(MSGPACK, vrefbuffer_unsigned_char)
{
  msgpack::vrefbuffer vbuf;
  GEN_TEST_VREF(unsigned char, vbuf);
}

TEST(MSGPACK, vrefbuffer_short)
{
  msgpack::vrefbuffer vbuf;
  GEN_TEST_VREF(short, vbuf);
}

TEST(MSGPACK, vrefbuffer_int)
{
  msgpack::vrefbuffer vbuf;
  GEN_TEST_VREF(int, vbuf);
}

TEST(MSGPACK, vrefbuffer_long)
{
  msgpack::vrefbuffer vbuf;
  GEN_TEST_VREF(long, vbuf);
}

TEST(MSGPACK, vrefbuffer_long_long)
{
  msgpack::vrefbuffer vbuf;
  GEN_TEST_VREF(long long, vbuf);
}

TEST(MSGPACK, vrefbuffer_unsigned_short)
{
  msgpack::vrefbuffer vbuf;
  GEN_TEST_VREF(unsigned short, vbuf);
}

TEST(MSGPACK, vrefbuffer_unsigned_int)
{
  msgpack::vrefbuffer vbuf;
  GEN_TEST_VREF(unsigned int, vbuf);
}

TEST(MSGPACK, vrefbuffer_unsigned_long)
{
  msgpack::vrefbuffer vbuf;
  GEN_TEST_VREF(unsigned long, vbuf);
}

TEST(MSGPACK, vrefbuffer_unsigned_long_long)
{
  msgpack::vrefbuffer vbuf;
  GEN_TEST_VREF(unsigned long long, vbuf);
}

TEST(MSGPACK, vrefbuffer_uint8)
{
  msgpack::vrefbuffer vbuf;
  GEN_TEST_VREF(uint8_t, vbuf);
}

TEST(MSGPACK, vrefbuffer_uint16)
{
  msgpack::vrefbuffer vbuf;
  GEN_TEST_VREF(uint16_t, vbuf);
}

TEST(MSGPACK, vrefbuffer_uint32)
{
  msgpack::vrefbuffer vbuf;
  GEN_TEST_VREF(uint32_t, vbuf);
}

TEST(MSGPACK, vrefbuffer_uint64)
{
  msgpack::vrefbuffer vbuf;
  GEN_TEST_VREF(uint64_t, vbuf);
}

TEST(MSGPACK, vrefbuffer_int8)
{
  msgpack::vrefbuffer vbuf;
  GEN_TEST_VREF(int8_t, vbuf);
}

TEST(MSGPACK, vrefbuffer_int16)
{
  msgpack::vrefbuffer vbuf;
  GEN_TEST_VREF(int16_t, vbuf);
}

TEST(MSGPACK, vrefbuffer_int32)
{
  msgpack::vrefbuffer vbuf;
  GEN_TEST_VREF(int32_t, vbuf);
}

TEST(MSGPACK, vrefbuffer_int64)
{
  msgpack::vrefbuffer vbuf;
  GEN_TEST_VREF(int64_t, vbuf);
}

// small ref_size and chunk_size

TEST(MSGPACK, vrefbuffer_small_signed_char)
{
  msgpack::vrefbuffer vbuf(0, 0);
  GEN_TEST_VREF(signed char, vbuf);
}

TEST(MSGPACK, vrefbuffer_small_unsigned_char)
{
  msgpack::vrefbuffer vbuf(0, 0);
  GEN_TEST_VREF(unsigned char, vbuf);
}

TEST(MSGPACK, vrefbuffer_small_short)
{
  msgpack::vrefbuffer vbuf(0, 0);
  GEN_TEST_VREF(short, vbuf);
}

TEST(MSGPACK, vrefbuffer_small_int)
{
  msgpack::vrefbuffer vbuf(0, 0);
  GEN_TEST_VREF(int, vbuf);
}

TEST(MSGPACK, vrefbuffer_small_long)
{
  msgpack::vrefbuffer vbuf(0, 0);
  GEN_TEST_VREF(long, vbuf);
}

TEST(MSGPACK, vrefbuffer_small_long_long)
{
  msgpack::vrefbuffer vbuf(0, 0);
  GEN_TEST_VREF(long long, vbuf);
}

TEST(MSGPACK, vrefbuffer_small_unsigned_short)
{
  msgpack::vrefbuffer vbuf(0, 0);
  GEN_TEST_VREF(unsigned short, vbuf);
}

TEST(MSGPACK, vrefbuffer_small_unsigned_int)
{
  msgpack::vrefbuffer vbuf(0, 0);
  GEN_TEST_VREF(unsigned int, vbuf);
}

TEST(MSGPACK, vrefbuffer_small_unsigned_long)
{
  msgpack::vrefbuffer vbuf(0, 0);
  GEN_TEST_VREF(unsigned long, vbuf);
}

TEST(MSGPACK, vrefbuffer_small_unsigned_long_long)
{
  msgpack::vrefbuffer vbuf(0, 0);
  GEN_TEST_VREF(unsigned long long, vbuf);
}

TEST(MSGPACK, vrefbuffer_small_uint8)
{
  msgpack::vrefbuffer vbuf(0, 0);
  GEN_TEST_VREF(uint8_t, vbuf);
}

TEST(MSGPACK, vrefbuffer_small_uint16)
{
  msgpack::vrefbuffer vbuf(0, 0);
  GEN_TEST_VREF(uint16_t, vbuf);
}

TEST(MSGPACK, vrefbuffer_small_uint32)
{
  msgpack::vrefbuffer vbuf(0, 0);
  GEN_TEST_VREF(uint32_t, vbuf);
}

TEST(MSGPACK, vrefbuffer_small_uint64)
{
  msgpack::vrefbuffer vbuf(0, 0);
  GEN_TEST_VREF(uint64_t, vbuf);
}

TEST(MSGPACK, vrefbuffer_small_int8)
{
  msgpack::vrefbuffer vbuf(0, 0);
  GEN_TEST_VREF(int8_t, vbuf);
}

TEST(MSGPACK, vrefbuffer_small_int16)
{
  msgpack::vrefbuffer vbuf(0, 0);
  GEN_TEST_VREF(int16_t, vbuf);
}

TEST(MSGPACK, vrefbuffer_small_int32)
{
  msgpack::vrefbuffer vbuf(0, 0);
  GEN_TEST_VREF(int32_t, vbuf);
}

TEST(MSGPACK, vrefbuffer_small_int64)
{
  msgpack::vrefbuffer vbuf(0, 0);
  GEN_TEST_VREF(int64_t, vbuf);
}


#include "msgpack.hpp"

#include <cmath>
#include <string>
#include <vector>
#include <map>
#include <deque>
#include <set>
#include <list>
#include <limits>

#include <gtest/gtest.h>

#ifdef HAVE_CONFIG_H
#include "config.h"
#endif

using namespace std;

#define GEN_TEST_VREF(test_type, vbuf)                                  \
  do {                                                                  \
    vector<test_type> v;                                                \
    v.push_back(0);                                                     \
    for (unsigned int i = 0; i < v.size(); i++) {                       \
      test_type val1 = v[i];                                            \
      msgpack::pack(vbuf, val1);                                        \
      msgpack::sbuffer sbuf;                                            \
      const struct iovec* cur = vbuf.vector();                          \
      const struct iovec* end = cur + vbuf.vector_size();               \
      for(; cur != end; ++cur)                                          \
        sbuf.write((const char*)cur->iov_base, cur->iov_len);           \
      msgpack::unpacked ret;                                            \
      msgpack::unpack(ret, sbuf.data(), sbuf.size());                   \
      test_type val2 = ret.get().as<test_type>();                       \
      EXPECT_EQ(val1, val2);                                            \
    }                                                                   \
  } while(0);

TEST(MSGPACK, vrefbuffer_char)
{
  msgpack::vrefbuffer vbuf;
  GEN_TEST_VREF(char, vbuf);
}

TEST(MSGPACK, vrefbuffer_signed_char)
{
  msgpack::vrefbuffer vbuf;
  GEN_TEST_VREF(signed char, vbuf);
}

TEST(MSGPACK, vrefbuffer_unsigned_char)
{
  msgpack::vrefbuffer vbuf;
  GEN_TEST_VREF(unsigned char, vbuf);
}

TEST(MSGPACK, vrefbuffer_short)
{
  msgpack::vrefbuffer vbuf;
  GEN_TEST_VREF(short, vbuf);
}

TEST(MSGPACK, vrefbuffer_int)
{
  msgpack::vrefbuffer vbuf;
  GEN_TEST_VREF(int, vbuf);
}

TEST(MSGPACK, vrefbuffer_long)
{
  msgpack::vrefbuffer vbuf;
  GEN_TEST_VREF(long, vbuf);
}

TEST(MSGPACK, vrefbuffer_long_long)
{
  msgpack::vrefbuffer vbuf;
  GEN_TEST_VREF(long long, vbuf);
}

TEST(MSGPACK, vrefbuffer_unsigned_short)
{
  msgpack::vrefbuffer vbuf;
  GEN_TEST_VREF(unsigned short, vbuf);
}

TEST(MSGPACK, vrefbuffer_unsigned_int)
{
  msgpack::vrefbuffer vbuf;
  GEN_TEST_VREF(unsigned int, vbuf);
}

TEST(MSGPACK, vrefbuffer_unsigned_long)
{
  msgpack::vrefbuffer vbuf;
  GEN_TEST_VREF(unsigned long, vbuf);
}

TEST(MSGPACK, vrefbuffer_unsigned_long_long)
{
  msgpack::vrefbuffer vbuf;
  GEN_TEST_VREF(unsigned long long, vbuf);
}

TEST(MSGPACK, vrefbuffer_uint8)
{
  msgpack::vrefbuffer vbuf;
  GEN_TEST_VREF(uint8_t, vbuf);
}

TEST(MSGPACK, vrefbuffer_uint16)
{
  msgpack::vrefbuffer vbuf;
  GEN_TEST_VREF(uint16_t, vbuf);
}

TEST(MSGPACK, vrefbuffer_uint32)
{
  msgpack::vrefbuffer vbuf;
  GEN_TEST_VREF(uint32_t, vbuf);
}

TEST(MSGPACK, vrefbuffer_uint64)
{
  msgpack::vrefbuffer vbuf;
  GEN_TEST_VREF(uint64_t, vbuf);
}

TEST(MSGPACK, vrefbuffer_int8)
{
  msgpack::vrefbuffer vbuf;
  GEN_TEST_VREF(int8_t, vbuf);
}

TEST(MSGPACK, vrefbuffer_int16)
{
  msgpack::vrefbuffer vbuf;
  GEN_TEST_VREF(i

nt16_t, vbuf);
}

TEST(MSGPACK, vrefbuffer_int32)
{
  msgpack::vrefbuffer vbuf;
  GEN_TEST_VREF(int32_t, vbuf);
}

TEST(MSGPACK, vrefbuffer_int64)
{
  msgpack::vrefbuffer vbuf;
  GEN_TEST_VREF(int64_t, vbuf);
}

// small ref_size and chunk_size
TEST(MSGPACK, vrefbuffer_small_char)
{
  msgpack::vrefbuffer vbuf(0, 0);
  GEN_TEST_VREF(char, vbuf);
}

TEST(MSGPACK, vrefbuffer_small_signed_char)
{
  msgpack::vrefbuffer vbuf(0, 0);
  GEN_TEST_VREF(signed char, vbuf);
}

TEST(MSGPACK, vrefbuffer_small_unsigned_char)
{
  msgpack::vrefbuffer vbuf(0, 0);
  GEN_TEST_VREF(unsigned char, vbuf);
}

TEST(MSGPACK, vrefbuffer_small_short)
{
  msgpack::vrefbuffer vbuf(0, 0);
  GEN_TEST_VREF(short, vbuf);
}

TEST(MSGPACK, vrefbuffer_small_int)
{
  msgpack::vrefbuffer vbuf(0, 0);
  GEN_TEST_VREF(int, vbuf);
}

TEST(MSGPACK, vrefbuffer_small_long)
{
  msgpack::vrefbuffer vbuf(0, 0);
  GEN_TEST_VREF(long, vbuf);
}

TEST(MSGPACK, vrefbuffer_small_long_long)
{
  msgpack::vrefbuffer vbuf(0, 0);
  GEN_TEST_VREF(long long, vbuf);
}

TEST(MSGPACK, vrefbuffer_small_unsigned_short)
{
  msgpack::vrefbuffer vbuf(0, 0);
  GEN_TEST_VREF(unsigned short, vbuf);
}

TEST(MSGPACK, vrefbuffer_small_unsigned_int)
{
  msgpack::vrefbuffer vbuf(0, 0);
  GEN_TEST_VREF(unsigned int, vbuf);
}

TEST(MSGPACK, vrefbuffer_small_unsigned_long)
{
  msgpack::vrefbuffer vbuf(0, 0);
  GEN_TEST_VREF(unsigned long, vbuf);
}

TEST(MSGPACK, vrefbuffer_small_unsigned_long_long)
{
  msgpack::vrefbuffer vbuf(0, 0);
  GEN_TEST_VREF(unsigned long long, vbuf);
}

TEST(MSGPACK, vrefbuffer_small_uint8)
{
  msgpack::vrefbuffer vbuf(0, 0);
  GEN_TEST_VREF(uint8_t, vbuf);
}

TEST(MSGPACK, vrefbuffer_small_uint16)
{
  msgpack::vrefbuffer vbuf(0, 0);
  GEN_TEST_VREF(uint16_t, vbuf);
}

TEST(MSGPACK, vrefbuffer_small_uint32)
{
  msgpack::vrefbuffer vbuf(0, 0);
  GEN_TEST_VREF(uint32_t, vbuf);
}

TEST(MSGPACK, vrefbuffer_small_uint64)
{
  msgpack::vrefbuffer vbuf(0, 0);
  GEN_TEST_VREF(uint64_t, vbuf);
}

TEST(MSGPACK, vrefbuffer_small_int8)
{
  msgpack::vrefbuffer vbuf(0, 0);
  GEN_TEST_VREF(int8_t, vbuf);
}

TEST(MSGPACK, vrefbuffer_small_int16)
{
  msgpack::vrefbuffer vbuf(0, 0);
  GEN_TEST_VREF(int16_t, vbuf);
}

TEST(MSGPACK, vrefbuffer_small_int32)
{
  msgpack::vrefbuffer vbuf(0, 0);
  GEN_TEST_VREF(int32_t, vbuf);
}

TEST(MSGPACK, vrefbuffer_small_int64)
{
  msgpack::vrefbuffer vbuf(0, 0);
  GEN_TEST_VREF(int64_t, vbuf);
}


void draw_framebuffer_popup(Registry& registry, ViewportPanel& data)

/*
 */

#include <lagrange/Logger.h>
#include <lagrange/ui/components/CameraComponents.h>
#include <lagrange/ui/components/Common.h>
#include <lagrange/ui/components/Viewport.h>
#include <lagrange/ui/imgui/UIWidget.h>
#include <lagrange/ui/imgui/buttons.h>
#include <lagrange/ui/panels/ViewportPanel.h>
#include <lagrange/ui/systems/render_viewports.h>
#include <lagrange/ui/systems/update_gizmo.h>
#include <lagrange/ui/systems/update_scene_bounds.h>
#include <lagrange/ui/types/Camera.h>
#include <lagrange/ui/types/Systems.h>
#include <lagrange/ui/utils/bounds.h>
#include <lagrange/ui/utils/input.h>
#include <lagrange/ui/utils/layer.h>
#include <lagrange/ui/utils/selection.h>
#include <lagrange/ui/utils/uipanel.h>
#include <lagrange/ui/utils/viewport.h>
#include <lagrange/ui/default_events.h>
#include <lagrange/ui/utils/events.h>

#include <IconsFontAwesome5.h>
#include <imgui.h>

namespace lagrange {
namespace ui {

namespace {

struct NoPadding
{
    NoPadding() { ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(0, 0)); }
    ~NoPadding() { ImGui::PopStyleVar(); }
};

void draw_imgui_gl_texture(GLuint tex_id, int w, int h)
{
    const ImTextureID texID = reinterpret_cast<void*>((long long int)(tex_id));

    const ImVec2 uv0 = ImVec2(0, 1);
    const ImVec2 uv1 = ImVec2(1, 0);

    ImGui::Image(
        texID,
        ImVec2(float(w), float(h)),
        uv0,
        uv1,
        ImVec4(1.0f, 1.0f, 1.0f, 1.0f),
        ImVec4(1.0f, 1.0f, 1.0f, 0.5f));
}

void separator()
{
    const ImVec2 p = ImGui::GetCursorScreenPos();
    ImGui::GetWindowDrawList()->AddLine(
        ImVec2(p.x, p.y),
        ImVec2(p.x, p.y + ImGui::GetTextLineHeightWithSpacing()),
        ImColor(ImGui::Spectrum::GRAY300),
        1.0f);
    ImGui::Dummy(ImVec2(2.5f, 0));
    ImGui::SameLine();
}
void draw_texture_widget(Texture& tex)
{
    auto w = tex.get_width();
    auto h = tex.get_height();
    if (w > 0 && h > 0) {
        const auto display_w = static_cast<int>(ImGui::GetContentRegionAvail().y - 20.0f);
        const auto display_h = static_cast<int>((float(h) / w) * display_w);

        const auto& p = tex.get_params();

        if (p.type == GL_TEXTURE_CUBE_MAP) {
            ImGui::Text("Cubemap texture widget not implemented");
        } else {
            draw_imgui_gl_texture(tex.get_id(), display_w, display_h);
        }

        ImGui::Text("Width: %d, Height: %d", w, h);

        ImGui::Text("Type: ");
        ImGui::SameLine();
        switch (p.type) {
        case GL_TEXTURE_1D: ImGui::Text("GL_TEXTURE_1D"); break;
        case GL_TEXTURE_2D: ImGui::Text("GL_TEXTURE_2D"); break;
        case GL_TEXTURE_3D: ImGui::Text("GL_TEXTURE_3D"); break;
        case GL_TEXTURE_2D_MULTISAMPLE: ImGui::Text("GL_TEXTURE_2D_MULTISAMPLE"); break;
        case GL_TEXTURE_CUBE_MAP: ImGui::Text("GL_TEXTURE_CUBE_MAP"); break;
        default: ImGui::Text("%x", p.type); break;
        }

        ImGui::Text("Format: ");
        ImGui::SameLine();
        switch (p.format) {
        case GL_RGB: ImGui::Text("GL_RGB"); break;
        case GL_RED: ImGui::Text("GL_RED"); break;
        case GL_RGBA: ImGui::Text("GL_RGBA"); break;
        case GL_DEPTH_COMPONENT: ImGui::Text("GL_DEPTH_COMPONENT"); break;
        default: ImGui::Text("Other: %x", p.format); break;
        }

        ImGui::Text("Internal Format: ");
        ImGui::SameLine();
        switch (p.internal_format) {
        case GL_R8: ImGui::Text("GL_R8"); break;
        case GL_RGB: ImGui::Text("GL_RGB"); break;
        case GL_RGBA: ImGui::Text("GL_RGBA"); break;
        case GL_SRGB_ALPHA: ImGui::Text("GL_SRGB_ALPHA"); break;
        case GL_SRGB: ImGui::Text("GL_SRGB"); break;
        case GL_SRGB8: ImGui::Text("GL_SRGB8"); break;
        case GL_DEPTH_COMPONENT24: ImGui::Text("GL_DEPTH_COMPONENT24"); break;
        case GL_RGB16F: ImGui::Text("GL_RGB16F"); break;
        case GL_RGB32F: ImGui::Text("GL_RGB32F"); break;
        default: ImGui::Text("Other: %x", p.format); break;
        }

        ImGui::Text("Generate Mipmap: %s", p.generate_mipmap ? "True" : "False");
        ImGui::Text("sRGB: %s", p.sRGB ? "True" : "False");

        auto label = string_format("Texture ID: {}", tex.get_id());
        ImGui::Text("Texture ID: %u", tex.get_id());
    }
}

void draw_render_pass_popup(
    [[maybe_unused]] Registry& registry,
    [[maybe_unused]] ViewportPanel& data)
{
#ifdef LGUI_RENDERER_DEPRECATED
    if (!ImGui::BeginPopupContextItem(render_pass_popup_name(registry, data).c_str())) return;

    if (ImGui::Button("Close")) ImGui::CloseCurrentPopup();

    ImGui::Dummy(ImVec2(400, 0));

    auto& viewport = registry.get<ViewportComponent>(data.viewport);

    auto& renderer = *viewport.renderer;

    auto& all_passes = renderer.get_pipeline().get_passes();

    auto display_pass = [&](RenderPassBase* pass) {
        const auto& display_name = pass->get_name();
        bool enabled = is_render_pass_enabled(viewport, pass);

        if (ImGui::Checkbox(display_name.c_str(), &enabled)) {
            enable_render_pass(viewport, pass, enabled);
        }

        for (const auto& tag : pass->get_tags()) {
            ImGui::SameLine();
            ImGui::TextColored(ImColor(ImGui::Spectrum::GRAY500).Value, "[%s]", tag.c_str());
        }

        if (pass->get_options().get_children().size() > 0 ||
            pass->get_options().get_options().size() > 0) {
            ImGui::SameLine();
            if (ImGui::TreeNode(("##" + display_name).c_str())) {
                UIWidget()(pass->get_options());

                auto deps = renderer.get_pipeline().get_dependencies({pass});
                if (deps.size() > 0) {
                    ImGui::Separator();
                    ImGui::Text("Dependencies (%d):", int(deps.size()));
                    for (auto* dep : deps) {
                        ImGui::Text("\t%s", dep->get_name().c_str());
                    }
                }

                ImGui::TreePop();
            }
        }
    };

    if (ImGui::TreeNode("Default")) {
        for (auto& pass_ptr : all_passes) {
            if (!pass_ptr->has_tag("default")) continue;
            display_pass(pass_ptr.get());
        }
        ImGui::TreePop();
    }

    ImGui::SetNextItemOpen(true, ImGuiCond_Once);
    if (ImGui::TreeNode("Custom")) {
        for (auto& pass_ptr : all_passes) {
            if (pass_ptr->has_tag("default")) continue;
            display_pass(pass_ptr.get());
        }
        ImGui::TreePop();
    }

    ImGui::EndPopup();
#endif
}

{
    ImGui::PushID("viewportopt");
    if (ImGui::Button("Viewport " ICON_FA_CARET_DOWN)) {
        ImGui::OpenPopup("viewportopt");
    }

    ImGui::SameLine();

    if (ImGui::BeginPopupContextItem("viewportopt")) {
        ImGui::Dummy(ImVec2(400, 0));

        registry.view<ViewportComponent>().each([&](Entity e, ViewportComponent& v) {
            ImGui::PushID(int(e));

            bool sel = data.viewport == e;
            if (ImGui::Checkbox(ui::get_name(registry, e).c_str(), &sel)) {
                if (sel) data.viewport = e;
            }

            ImGui::Indent();

            if (ImGui::CollapsingHeader("Viewport Options")) {
                ImGui::InputInt("Width", &v.width);
                ImGui::InputInt("Height", &v.height);
                ImGui::Checkbox("Auto near/far", &v.auto_nearfar);

                if (v.auto_nearfar) {
                    auto n = v.computed_camera.get_near();
                    auto f = v.computed_camera.get_far();
                    ImGui::InputFloat("Computed near", &n);
                    ImGui::InputFloat("Computed far", &f);
                }
            }

            if (ImGui::CollapsingHeader("Layer visibility")) {
                for (size_t i = 0; i < get_max_layers(); i++) {
                    const auto& name = get_layer_name(registry, LayerIndex(i));
                    if (name.length() == 0) continue;

                    bool value = v.visible_layers.test(i);
                    if (ImGui::Checkbox(name.c_str(), &value)) {
                        v.visible_layers.flip(i);
                    }
                }
            }

            if (ImGui::CollapsingHeader("Post process effects")) {
                for (auto& it : v.post_process_effects) {
                    ImGui::Text("%s", it.first.c_str());
                }
            }

            if (v.fbo) {
                auto max_colors = FrameBuffer::get_max_color_attachments();

                if (ImGui::CollapsingHeader("Color attachments")) {
                    for (auto i = 0; i < max_colors; i++) {
                        ImGui::Text("[Color %d] Attachment", i);
                        auto ptr = v.fbo->get_color_attachement(i);
                        if (ptr) {
                            draw_texture_widget(*ptr);
                        }
                    }
                }

                if (ImGui::CollapsingHeader("Depth attachment")) {
                    auto ptr = v.fbo->get_depth_attachment();
                    if (ptr) {
                        draw_texture_widget(*ptr);
                    }
                }
            }

            // Layers

            /*  for (auto& p : v.post_process_effects) {
                  ImGui::Text("Post process effect");
              }*/

            ImGui::Unindent();

            ImGui::PopID();
        });

        ImGui::EndPopup();
    }

    ImGui::PopID();
}

void draw_viewport_toolbar(Registry& registry, ViewportPanel& data)
{
    auto& keys = get_keybinds(registry);
    auto& viewport = registry.get<ViewportComponent>(data.viewport);
    auto& cam = get_viewport_camera(registry, viewport);

    // Add padding, as window padding is disabled
    ImGui::Dummy(ImVec2(5, 1));
    ImGui::Dummy(ImVec2(1, 5));
    ImGui::SameLine();

    /*
       Render appearence
   */
#ifdef LGUI_RENDERER_DEPRECATED
    if (viewport.renderer) {
        const bool pbr = is_render_pass_enabled_tag(viewport, "pbr");
        const bool edges = is_render_pass_enabled(viewport, "Edges");
        const bool vertices = is_render_pass_enabled(viewport, "Vertices");
        const bool normal = is_render_pass_enabled_tag(viewport, "normal");
        const bool bbox = is_render_pass_enabled_tag(viewport, "boundingbox");

        if (button(pbr, ICON_FA_LIGHTBULB, "Physically Based Render")) {
            enable_render_pass_tag(viewport, "pbr", !pbr);
        }
        ImGui::SameLine();

        if (button(edges, ICON_FA_ARROWS_ALT_H, "Edges")) {
            enable_render_pass(viewport, "Edges", !edges);
        }
        ImGui::SameLine();

        if (button(vertices, ICON_FA_CIRCLE, "Vertices")) {
            enable_render_pass(viewport, "Vertices", !vertices);
        }
        ImGui::SameLine();

        if (button(normal, ICON_FA_EXTERNAL_LINK_ALT, "Normals")) {
            enable_render_pass_tag(viewport, "normal", !normal);
        }
        ImGui::SameLine();

        if (button(bbox, ICON_FA_VECTOR_SQUARE, "Bounding Box")) {
            enable_render_pass_tag(viewport, "boundingbox", !bbox);
        }
        ImGui::SameLine();
    }
#endif

/*
   Normals
*/
#ifdef LGUI_RENDERER_DEPRECATED
    if (viewport.renderer) {
        auto& renderer = *viewport.renderer;
        ImGui::PushID("normals");
        if (ImGui::Button(ICON_FA_CARET_DOWN)) {
            ImGui::OpenPopup("Normals");
        }

        ImGui::SameLine();

        if (ImGui::BeginPopupContextItem("Normals")) {
            auto* pass = renderer.get_pipeline().get_pass(default_render_pass_name<NormalsPass>());
            auto& opt = pass->get_options();

            float w = 250.0f;
            bool face = opt["Face"].get<bool>("Enabled");
            if (ImGui::Selectable(
                    ICON_FA_EXTERNAL_LINK_ALT " Face Normals",
                    face,
                    0,
                    ImVec2(w, 0))) {
                opt["Face"].set<bool>("Enabled", !face);
            }

            bool corner = opt["Corner Vertex"].get<bool>("Enabled");
            if (ImGui::Selectable(
                    ICON_FA_EXTERNAL_LINK_SQUARE_ALT "   Vertex Corner Normals",
                    corner,
                    0,
                    ImVec2(w, 0))) {
                opt["Corner Vertex"].set<bool>("Enabled", !corner);
            }

            bool pervertex = opt["Per-Vertex"].get<bool>("Enabled");
            if (ImGui::Selectable(
                    ICON_FA_ASTERISK "  Per-Vertex Normals",
                    pervertex,
                    0,
                    ImVec2(w, 0))) {
                opt["Per-Vertex"].set<bool>("Enabled", !pervertex);
            }
            ImGui::EndPopup();
        }
        ImGui::PopID();

        separator();
    }

    /*
        Post processing
    */
    if (viewport.renderer) {
        const bool outline = is_render_pass_enabled_tag(viewport, "outline");
        const bool fxaa = is_render_pass_enabled(viewport, default_render_pass_name<FXAAPass>());

        if (button(outline, ICON_FA_OBJECT_GROUP, "Selection Outline")) {
            enable_render_pass_tag(viewport, "outline", !outline);
        }
        ImGui::SameLine();

        if (button(fxaa, "AA", "FXAA")) {
            enable_render_pass(viewport, default_render_pass_name<FXAAPass>(), !fxaa);
        }
        ImGui::SameLine();

        separator();
    }

    /*
        Render pass details
    */
    if (viewport.renderer) {
        // Get unique name
        if (ImGui::Button("Render passes " ICON_FA_CARET_DOWN)) {
            ImGui::OpenPopup(render_pass_popup_name(registry, data).c_str());
        }
        ImGui::SameLine();
        separator();
    }

#endif

    /*
        Camera
    */
    if (registry.valid(viewport.camera_reference) &&
        registry.has<CameraController>(viewport.camera_reference)) {
        auto& controller = registry.get<CameraController>(viewport.camera_reference);

        bool changed = false;

        // Camera modes
        {
            const bool perspective = (cam.get_type() == Camera::Type::PERSPECTIVE);

            if (button_icon(perspective, ICON_FA_LESS_THAN, "Perspective")) {
                if (!perspective)
                    cam.set_type(Camera::Type::PERSPECTIVE);
                else
                    cam.set_type(Camera::Type::ORTHOGRAPHIC);
                changed = true;
            }
            ImGui::SameLine();

            if (button_icon(!perspective, ICON_FA_BARS, "Orthographic")) {
                if (!perspective)
                    cam.set_type(Camera::Type::PERSPECTIVE);
                else
                    cam.set_type(Camera::Type::ORTHOGRAPHIC);
                changed = true;
            }
            ImGui::SameLine();

            if (!perspective) {
                if (button_icon(
                        controller.ortho_interaction_2D,
                        "2D",
                        "2D Orthographic Camera Interaction")) {
                    controller.ortho_interaction_2D = !controller.ortho_interaction_2D;
                }
                ImGui::SameLine();
                if (button_icon(
                        !controller.ortho_interaction_2D,
                        "3D",
                        "3D Orthographic Camera Interaction")) {
                    controller.ortho_interaction_2D = !controller.ortho_interaction_2D;
                }
                ImGui::SameLine();
            }
        }

        // Camera direction
        {
            if (button_icon(
                    cam.is_orthogonal_direction(Camera::Dir::TOP),
                    "Top",
                    "Top-Down View")) {
                cam.set_orthogonal_direction(Camera::Dir::TOP);
                changed = true;
            }
            ImGui::SameLine();

            if (button_icon(cam.is_orthogonal_direction(Camera::Dir::BOTTOM), "Down", "Up View")) {
                cam.set_orthogonal_direction(Camera::Dir::BOTTOM);
                changed = true;
            }
            ImGui::SameLine();

            if (button_icon(
                    cam.is_orthogonal_direction(Camera::Dir::FRONT),
                    "Front",
                    "Front View")) {
                cam.set_orthogonal_direction(Camera::Dir::FRONT);
                changed = true;
            }
            ImGui::SameLine();

            if (button_icon(cam.is_orthogonal_direction(Camera::Dir::LEFT), "Left", "Left View")) {
                cam.set_orthogonal_direction(Camera::Dir::LEFT);
                changed = true;
            }
            ImGui::SameLine();

            if (button_icon(cam.is_orthogonal_direction(Camera::Dir::BACK), "Back", "Back View")) {
                cam.set_orthogonal_direction(Camera::Dir::BACK);
                changed = true;
            }
            ImGui::SameLine();

            if (button_icon(
                    cam.is_orthogonal_direction(Camera::Dir::RIGHT),
                    "Right",
                    "Right View")) {
                cam.set_orthogonal_direction(Camera::Dir::RIGHT);
                changed = true;
            }
            ImGui::SameLine();
        }

        auto view = registry.view<CameraController, Camera>();

        for (auto e : view) {
            if (changed)
                ui::publish<CameraChangedEvent>(registry, e);
        }

        // Multi viewport
        {
            if (button_icon(false, ICON_FA_SHARE_SQUARE, "Instance camera to other viewports")) {
                instance_camera_to_viewports(registry, viewport.camera_reference);
            }
            ImGui::SameLine();

            if (button_icon(false, ICON_FA_SHARE, "Copy camera to other viewports")) {
                copy_camera_to_viewports(registry, viewport.camera_reference);
            }
            ImGui::SameLine();
        }

        {
            bool fit = false;
            bool focus = false;
            if (button_icon(
                    false,
                    ICON_FA_COMPRESS_ARROWS_ALT,
                    "Focus On Selection",
                    "global.camera.center_on_selection",
                    &keys)) {
                focus = true;
            }
            ImGui::SameLine();

            if (button_icon(
                    false,
                    ICON_FA_EXPAND,
                    "Zoom To Fit Selection",
                    "global.camera.zoom_to_fit",
                    &keys)) {
                fit = true;
                focus = true;
            }

            if ((fit || focus) && registry.valid(viewport.camera_reference)) {
                camera_focus_and_fit(
                    registry,
                    viewport.camera_reference,
                    focus,
                    fit,
                    1.0f,
                    [](Registry& r, Entity e) { return is_selected(r, e); });
            }

            ImGui::SameLine();
        }

        if (button_icon(!controller.fov_zoom, ICON_FA_ARROWS_ALT_V, "Dolly")) {
            controller.fov_zoom = !controller.fov_zoom;
        }

        ImGui::SameLine();

        separator();

        if (button_icon(controller.auto_nearfar, ICON_FA_COMPRESS, "Automatic Clipping Planes")) {
            controller.auto_nearfar = !controller.auto_nearfar;
        }

        ImGui::SameLine();

        separator();
    }

#ifdef LGUI_RENDERER_DEPRECATED
    /*
        Ground rendering
    */
    if (viewport.renderer) {
        auto& renderer = *viewport.renderer;
        bool ground_pass = is_render_pass_enabled(viewport, default_render_pass_name<GroundPass>());
        if (button(ground_pass, ICON_FA_TH, "Toggle Ground")) {
            enable_render_pass(viewport, default_render_pass_name<GroundPass>(), !ground_pass);
        }

        ImGui::SameLine();

        // Ground options
        {
            ImGui::PushID("groundopt");
            if (ImGui::Button(ICON_FA_CARET_DOWN)) {
                ImGui::OpenPopup("Ground");
            }
            ImGui::SameLine();

            if (ImGui::BeginPopupContextItem("Ground")) {
                ImGui::Dummy(ImVec2(400, 0));
                UIWidget("Grid Options")(
                    renderer.get_default_pass<DefaultPasses::PASS_GROUND>()->get_options(),
                    "",
                    0,
                    false);

                ImGui::EndPopup();
            }

            ImGui::PopID();
        }

        separator();
    }
#endif

    draw_framebuffer_popup(registry, data);

    separator();

    ImGui::Dummy(ImVec2(0, 0));
}

void draw_viewport_texture(ViewportComponent& viewport)
{
    Texture* texture = nullptr;
    if (viewport.fbo->has_color_attachment()) {
        texture = viewport.fbo->get_color_attachement(0).get();
    } else if (viewport.fbo->has_depth_attachement()) {
        texture = viewport.fbo->get_depth_attachment().get();
    }
    if (!texture) {
        ImGui::Text("No framebuffer attachement");
        return;
    }

    draw_imgui_gl_texture(texture->get_id(), viewport.width, viewport.height);
}

void viewport_panel_system(Registry& registry, Entity e)
{
    ViewportPanel& data = registry.get<ViewportPanel>(e);
    auto& input = get_input(registry);
    if (!registry.valid(data.viewport) || !registry.has<ViewportComponent>(data.viewport)) {
        ImGui::Text("Invalid viewport");
        return;
    }
    auto& viewport = registry.get<ViewportComponent>(data.viewport);

    // Update FocusedViewportPanel
    if (registry.get<UIPanel>(e).is_focused) {
        registry.ctx<FocusedViewportPanel>().viewport_panel = e;
    }

    Camera& cam = get_viewport_camera(registry, viewport);

    ImGui::PushID(int(e));

    // Draw render pass popup
    draw_render_pass_popup(registry, data);

    // Draw toolbar
    if (data.show_viewport_toolbar) {
        draw_viewport_toolbar(registry, data);
    }

    {
        NoPadding _;
        // Look at current imgui state
        data.canvas_origin = ImGui::GetCursorScreenPos();
        data.available_width = std::max(16, static_cast<int>(ImGui::GetContentRegionAvail().x));
        data.available_height =
            std::max(16, static_cast<int>(ImGui::GetContentRegionAvail().y - 2));

        // Update viewport dimensions
        viewport.width = data.available_width;
        viewport.height = data.available_height;

        // Update camera dimensions (needed in camera controller)
        // TODO: camera controller shouldn't care about pixels
        cam.set_window_dimensions(float(viewport.width), float(viewport.height));

        // Draw the canvas/texture
        draw_viewport_texture(viewport);
    }

    // Compute mouse state
    data.hovered = ImGui::IsWindowHovered(ImGuiHoveredFlags_RootWindow) &&
                   data.is_over_viewport(input.mouse_position);
    data.mouse_in_canvas = data.screen_to_viewport(input.mouse_position);

    if (!registry.valid(viewport.camera_reference) ||
        !registry.has<CameraController>(viewport.camera_reference)) {
        ImGui::PopID();
        return;
    }

    CameraController& controller = registry.get<CameraController>(viewport.camera_reference);
    auto& keys = *input.keybinds;

    // If this viewport has focus, set draw list for gizmo here
    if (e == registry.ctx<FocusedViewportPanel>().viewport_panel) {
        gizmo_system_set_draw_list();
    }

    // Check for gizmo system being used by Tools
    bool hovered_no_gizmo = data.hovered && !gizmo_system_is_using() && !gizmo_system_is_over();

    if (hovered_no_gizmo) {
        if (keys.is_pressed("viewport.camera.rotate")) {
            if (!controller.rotation_active) {
                controller.rotation_mouse_start = data.mouse_in_canvas;
                controller.rotation_camera_pos_start = cam.get_position();
                controller.rotation_camera_up_start = cam.get_up();
            }
            controller.rotation_active = true;
        }

        // Zoom using mousewheel
        if (input.mouse_wheel != 0.0f) {
            controller.dolly_active = true;
            controller.dolly_delta = static_cast<float>(0.15f * input.mouse_wheel);
        } else {
            controller.dolly_active = false;
        }

        // Zoom using dolly keybind
        if (keys.is_down("viewport.camera.dolly")) {
            controller.dolly_active = true;
            controller.dolly_delta = float(input.mouse_delta.x()) / cam.get_window_width();
        }

        if (keys.is_down("viewport.camera.pan")) {
            controller.pan_active = true;
        }
    }

    if (keys.is_released("viewport.camera.rotate")) {
        controller.rotation_active = false;
    }

    if (keys.is_released("viewport.camera.dolly")) {
        controller.dolly_active = false;
    }

    if (keys.is_released("viewport.camera.pan")) {
        controller.pan_active = false;
    }

    controller.mouse_current = data.mouse_in_canvas;
    controller.mouse_delta = input.mouse_delta;

    ImGui::PopID();
}

} // namespace

bool ViewportPanel::is_over_viewport(const Eigen::Vector2f& pos) const
{
    return pos.x() > canvas_origin.x() && pos.y() > canvas_origin.y() &&
           pos.x() < canvas_origin.x() + available_width &&
           pos.y() < canvas_origin.y() + available_height;
}

Eigen::Vector2f ViewportPanel::screen_to_viewport(const Eigen::Vector2f& pos) const
{
    return {pos.x() - canvas_origin.x(), available_height - (pos.y() - canvas_origin.y())};
}

Eigen::Vector2f ViewportPanel::viewport_to_screen(const Eigen::Vector2f& viewport_pos) const
{
    return {
        viewport_pos.x() + canvas_origin.x(),
        canvas_origin.y() + available_height - viewport_pos.y()};
}

Entity add_viewport_panel(Registry& r, const std::string& name /*= "Viewport"*/, Entity viewport)
{
    auto e = add_panel(r, name, viewport_panel_system);
    ViewportPanel vw;
    vw.viewport = viewport;
    r.emplace<ViewportPanel>(e, std::move(vw));
    return e;
}

} // namespace ui
} // namespace lagrange


{
    return {pos.x() - canvas_origin.x(), available_height - (pos.y() - canvas_origin.y())};
}

/*
 */

#include <lagrange/Logger.h>
#include <lagrange/ui/components/CameraComponents.h>
#include <lagrange/ui/components/Common.h>
#include <lagrange/ui/components/Viewport.h>
#include <lagrange/ui/imgui/UIWidget.h>
#include <lagrange/ui/imgui/buttons.h>
#include <lagrange/ui/panels/ViewportPanel.h>
#include <lagrange/ui/systems/render_viewports.h>
#include <lagrange/ui/systems/update_gizmo.h>
#include <lagrange/ui/systems/update_scene_bounds.h>
#include <lagrange/ui/types/Camera.h>
#include <lagrange/ui/types/Systems.h>
#include <lagrange/ui/utils/bounds.h>
#include <lagrange/ui/utils/input.h>
#include <lagrange/ui/utils/layer.h>
#include <lagrange/ui/utils/selection.h>
#include <lagrange/ui/utils/uipanel.h>
#include <lagrange/ui/utils/viewport.h>
#include <lagrange/ui/default_events.h>
#include <lagrange/ui/utils/events.h>

#include <IconsFontAwesome5.h>
#include <imgui.h>

namespace lagrange {
namespace ui {

namespace {

struct NoPadding
{
    NoPadding() { ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(0, 0)); }
    ~NoPadding() { ImGui::PopStyleVar(); }
};

void draw_imgui_gl_texture(GLuint tex_id, int w, int h)
{
    const ImTextureID texID = reinterpret_cast<void*>((long long int)(tex_id));

    const ImVec2 uv0 = ImVec2(0, 1);
    const ImVec2 uv1 = ImVec2(1, 0);

    ImGui::Image(
        texID,
        ImVec2(float(w), float(h)),
        uv0,
        uv1,
        ImVec4(1.0f, 1.0f, 1.0f, 1.0f),
        ImVec4(1.0f, 1.0f, 1.0f, 0.5f));
}

void separator()
{
    const ImVec2 p = ImGui::GetCursorScreenPos();
    ImGui::GetWindowDrawList()->AddLine(
        ImVec2(p.x, p.y),
        ImVec2(p.x, p.y + ImGui::GetTextLineHeightWithSpacing()),
        ImColor(ImGui::Spectrum::GRAY300),
        1.0f);
    ImGui::Dummy(ImVec2(2.5f, 0));
    ImGui::SameLine();
}
void draw_texture_widget(Texture& tex)
{
    auto w = tex.get_width();
    auto h = tex.get_height();
    if (w > 0 && h > 0) {
        const auto display_w = static_cast<int>(ImGui::GetContentRegionAvail().y - 20.0f);
        const auto display_h = static_cast<int>((float(h) / w) * display_w);

        const auto& p = tex.get_params();

        if (p.type == GL_TEXTURE_CUBE_MAP) {
            ImGui::Text("Cubemap texture widget not implemented");
        } else {
            draw_imgui_gl_texture(tex.get_id(), display_w, display_h);
        }

        ImGui::Text("Width: %d, Height: %d", w, h);

        ImGui::Text("Type: ");
        ImGui::SameLine();
        switch (p.type) {
        case GL_TEXTURE_1D: ImGui::Text("GL_TEXTURE_1D"); break;
        case GL_TEXTURE_2D: ImGui::Text("GL_TEXTURE_2D"); break;
        case GL_TEXTURE_3D: ImGui::Text("GL_TEXTURE_3D"); break;
        case GL_TEXTURE_2D_MULTISAMPLE: ImGui::Text("GL_TEXTURE_2D_MULTISAMPLE"); break;
        case GL_TEXTURE_CUBE_MAP: ImGui::Text("GL_TEXTURE_CUBE_MAP"); break;
        default: ImGui::Text("%x", p.type); break;
        }

        ImGui::Text("Format: ");
        ImGui::SameLine();
        switch (p.format) {
        case GL_RGB: ImGui::Text("GL_RGB"); break;
        case GL_RED: ImGui::Text("GL_RED"); break;
        case GL_RGBA: ImGui::Text("GL_RGBA"); break;
        case GL_DEPTH_COMPONENT: ImGui::Text("GL_DEPTH_COMPONENT"); break;
        default: ImGui::Text("Other: %x", p.format); break;
        }

        ImGui::Text("Internal Format: ");
        ImGui::SameLine();
        switch (p.internal_format) {
        case GL_R8: ImGui::Text("GL_R8"); break;
        case GL_RGB: ImGui::Text("GL_RGB"); break;
        case GL_RGBA: ImGui::Text("GL_RGBA"); break;
        case GL_SRGB_ALPHA: ImGui::Text("GL_SRGB_ALPHA"); break;
        case GL_SRGB: ImGui::Text("GL_SRGB"); break;
        case GL_SRGB8: ImGui::Text("GL_SRGB8"); break;
        case GL_DEPTH_COMPONENT24: ImGui::Text("GL_DEPTH_COMPONENT24"); break;
        case GL_RGB16F: ImGui::Text("GL_RGB16F"); break;
        case GL_RGB32F: ImGui::Text("GL_RGB32F"); break;
        default: ImGui::Text("Other: %x", p.format); break;
        }

        ImGui::Text("Generate Mipmap: %s", p.generate_mipmap ? "True" : "False");
        ImGui::Text("sRGB: %s", p.sRGB ? "True" : "False");

        auto label = string_format("Texture ID: {}", tex.get_id());
        ImGui::Text("Texture ID: %u", tex.get_id());
    }
}

void draw_render_pass_popup(
    [[maybe_unused]] Registry& registry,
    [[maybe_unused]] ViewportPanel& data)
{
#ifdef LGUI_RENDERER_DEPRECATED
    if (!ImGui::BeginPopupContextItem(render_pass_popup_name(registry, data).c_str())) return;

    if (ImGui::Button("Close")) ImGui::CloseCurrentPopup();

    ImGui::Dummy(ImVec2(400, 0));

    auto& viewport = registry.get<ViewportComponent>(data.viewport);

    auto& renderer = *viewport.renderer;

    auto& all_passes = renderer.get_pipeline().get_passes();

    auto display_pass = [&](RenderPassBase* pass) {
        const auto& display_name = pass->get_name();
        bool enabled = is_render_pass_enabled(viewport, pass);

        if (ImGui::Checkbox(display_name.c_str(), &enabled)) {
            enable_render_pass(viewport, pass, enabled);
        }

        for (const auto& tag : pass->get_tags()) {
            ImGui::SameLine();
            ImGui::TextColored(ImColor(ImGui::Spectrum::GRAY500).Value, "[%s]", tag.c_str());
        }

        if (pass->get_options().get_children().size() > 0 ||
            pass->get_options().get_options().size() > 0) {
            ImGui::SameLine();
            if (ImGui::TreeNode(("##" + display_name).c_str())) {
                UIWidget()(pass->get_options());

                auto deps = renderer.get_pipeline().get_dependencies({pass});
                if (deps.size() > 0) {
                    ImGui::Separator();
                    ImGui::Text("Dependencies (%d):", int(deps.size()));
                    for (auto* dep : deps) {
                        ImGui::Text("\t%s", dep->get_name().c_str());
                    }
                }

                ImGui::TreePop();
            }
        }
    };

    if (ImGui::TreeNode("Default")) {
        for (auto& pass_ptr : all_passes) {
            if (!pass_ptr->has_tag("default")) continue;
            display_pass(pass_ptr.get());
        }
        ImGui::TreePop();
    }

    ImGui::SetNextItemOpen(true, ImGuiCond_Once);
    if (ImGui::TreeNode("Custom")) {
        for (auto& pass_ptr : all_passes) {
            if (pass_ptr->has_tag("default")) continue;
            display_pass(pass_ptr.get());
        }
        ImGui::TreePop();
    }

    ImGui::EndPopup();
#endif
}

void draw_framebuffer_popup(Registry& registry, ViewportPanel& data)
{
    ImGui::PushID("viewportopt");
    if (ImGui::Button("Viewport " ICON_FA_CARET_DOWN)) {
        ImGui::OpenPopup("viewportopt");
    }

    ImGui::SameLine();

    if (ImGui::BeginPopupContextItem("viewportopt")) {
        ImGui::Dummy(ImVec2(400, 0));

        registry.view<ViewportComponent>().each([&](Entity e, ViewportComponent& v) {
            ImGui::PushID(int(e));

            bool sel = data.viewport == e;
            if (ImGui::Checkbox(ui::get_name(registry, e).c_str(), &sel)) {
                if (sel) data.viewport = e;
            }

            ImGui::Indent();

            if (ImGui::CollapsingHeader("Viewport Options")) {
                ImGui::InputInt("Width", &v.width);
                ImGui::InputInt("Height", &v.height);
                ImGui::Checkbox("Auto near/far", &v.auto_nearfar);

                if (v.auto_nearfar) {
                    auto n = v.computed_camera.get_near();
                    auto f = v.computed_camera.get_far();
                    ImGui::InputFloat("Computed near", &n);
                    ImGui::InputFloat("Computed far", &f);
                }
            }

            if (ImGui::CollapsingHeader("Layer visibility")) {
                for (size_t i = 0; i < get_max_layers(); i++) {
                    const auto& name = get_layer_name(registry, LayerIndex(i));
                    if (name.length() == 0) continue;

                    bool value = v.visible_layers.test(i);
                    if (ImGui::Checkbox(name.c_str(), &value)) {
                        v.visible_layers.flip(i);
                    }
                }
            }

            if (ImGui::CollapsingHeader("Post process effects")) {
                for (auto& it : v.post_process_effects) {
                    ImGui::Text("%s", it.first.c_str());
                }
            }

            if (v.fbo) {
                auto max_colors = FrameBuffer::get_max_color_attachments();

                if (ImGui::CollapsingHeader("Color attachments")) {
                    for (auto i = 0; i < max_colors; i++) {
                        ImGui::Text("[Color %d] Attachment", i);
                        auto ptr = v.fbo->get_color_attachement(i);
                        if (ptr) {
                            draw_texture_widget(*ptr);
                        }
                    }
                }

                if (ImGui::CollapsingHeader("Depth attachment")) {
                    auto ptr = v.fbo->get_depth_attachment();
                    if (ptr) {
                        draw_texture_widget(*ptr);
                    }
                }
            }

            // Layers

            /*  for (auto& p : v.post_process_effects) {
                  ImGui::Text("Post process effect");
              }*/

            ImGui::Unindent();

            ImGui::PopID();
        });

        ImGui::EndPopup();
    }

    ImGui::PopID();
}

void draw_viewport_toolbar(Registry& registry, ViewportPanel& data)
{
    auto& keys = get_keybinds(registry);
    auto& viewport = registry.get<ViewportComponent>(data.viewport);
    auto& cam = get_viewport_camera(registry, viewport);

    // Add padding, as window padding is disabled
    ImGui::Dummy(ImVec2(5, 1));
    ImGui::Dummy(ImVec2(1, 5));
    ImGui::SameLine();

    /*
       Render appearence
   */
#ifdef LGUI_RENDERER_DEPRECATED
    if (viewport.renderer) {
        const bool pbr = is_render_pass_enabled_tag(viewport, "pbr");
        const bool edges = is_render_pass_enabled(viewport, "Edges");
        const bool vertices = is_render_pass_enabled(viewport, "Vertices");
        const bool normal = is_render_pass_enabled_tag(viewport, "normal");
        const bool bbox = is_render_pass_enabled_tag(viewport, "boundingbox");

        if (button(pbr, ICON_FA_LIGHTBULB, "Physically Based Render")) {
            enable_render_pass_tag(viewport, "pbr", !pbr);
        }
        ImGui::SameLine();

        if (button(edges, ICON_FA_ARROWS_ALT_H, "Edges")) {
            enable_render_pass(viewport, "Edges", !edges);
        }
        ImGui::SameLine();

        if (button(vertices, ICON_FA_CIRCLE, "Vertices")) {
            enable_render_pass(viewport, "Vertices", !vertices);
        }
        ImGui::SameLine();

        if (button(normal, ICON_FA_EXTERNAL_LINK_ALT, "Normals")) {
            enable_render_pass_tag(viewport, "normal", !normal);
        }
        ImGui::SameLine();

        if (button(bbox, ICON_FA_VECTOR_SQUARE, "Bounding Box")) {
            enable_render_pass_tag(viewport, "boundingbox", !bbox);
        }
        ImGui::SameLine();
    }
#endif

/*
   Normals
*/
#ifdef LGUI_RENDERER_DEPRECATED
    if (viewport.renderer) {
        auto& renderer = *viewport.renderer;
        ImGui::PushID("normals");
        if (ImGui::Button(ICON_FA_CARET_DOWN)) {
            ImGui::OpenPopup("Normals");
        }

        ImGui::SameLine();

        if (ImGui::BeginPopupContextItem("Normals")) {
            auto* pass = renderer.get_pipeline().get_pass(default_render_pass_name<NormalsPass>());
            auto& opt = pass->get_options();

            float w = 250.0f;
            bool face = opt["Face"].get<bool>("Enabled");
            if (ImGui::Selectable(
                    ICON_FA_EXTERNAL_LINK_ALT " Face Normals",
                    face,
                    0,
                    ImVec2(w, 0))) {
                opt["Face"].set<bool>("Enabled", !face);
            }

            bool corner = opt["Corner Vertex"].get<bool>("Enabled");
            if (ImGui::Selectable(
                    ICON_FA_EXTERNAL_LINK_SQUARE_ALT "   Vertex Corner Normals",
                    corner,
                    0,
                    ImVec2(w, 0))) {
                opt["Corner Vertex"].set<bool>("Enabled", !corner);
            }

            bool pervertex = opt["Per-Vertex"].get<bool>("Enabled");
            if (ImGui::Selectable(
                    ICON_FA_ASTERISK "  Per-Vertex Normals",
                    pervertex,
                    0,
                    ImVec2(w, 0))) {
                opt["Per-Vertex"].set<bool>("Enabled", !pervertex);
            }
            ImGui::EndPopup();
        }
        ImGui::PopID();

        separator();
    }

    /*
        Post processing
    */
    if (viewport.renderer) {
        const bool outline = is_render_pass_enabled_tag(viewport, "outline");
        const bool fxaa = is_render_pass_enabled(viewport, default_render_pass_name<FXAAPass>());

        if (button(outline, ICON_FA_OBJECT_GROUP, "Selection Outline")) {
            enable_render_pass_tag(viewport, "outline", !outline);
        }
        ImGui::SameLine();

        if (button(fxaa, "AA", "FXAA")) {
            enable_render_pass(viewport, default_render_pass_name<FXAAPass>(), !fxaa);
        }
        ImGui::SameLine();

        separator();
    }

    /*
        Render pass details
    */
    if (viewport.renderer) {
        // Get unique name
        if (ImGui::Button("Render passes " ICON_FA_CARET_DOWN)) {
            ImGui::OpenPopup(render_pass_popup_name(registry, data).c_str());
        }
        ImGui::SameLine();
        separator();
    }

#endif

    /*
        Camera
    */
    if (registry.valid(viewport.camera_reference) &&
        registry.has<CameraController>(viewport.camera_reference)) {
        auto& controller = registry.get<CameraController>(viewport.camera_reference);

        bool changed = false;

        // Camera modes
        {
            const bool perspective = (cam.get_type() == Camera::Type::PERSPECTIVE);

            if (button_icon(perspective, ICON_FA_LESS_THAN, "Perspective")) {
                if (!perspective)
                    cam.set_type(Camera::Type::PERSPECTIVE);
                else
                    cam.set_type(Camera::Type::ORTHOGRAPHIC);
                changed = true;
            }
            ImGui::SameLine();

            if (button_icon(!perspective, ICON_FA_BARS, "Orthographic")) {
                if (!perspective)
                    cam.set_type(Camera::Type::PERSPECTIVE);
                else
                    cam.set_type(Camera::Type::ORTHOGRAPHIC);
                changed = true;
            }
            ImGui::SameLine();

            if (!perspective) {
                if (button_icon(
                        controller.ortho_interaction_2D,
                        "2D",
                        "2D Orthographic Camera Interaction")) {
                    controller.ortho_interaction_2D = !controller.ortho_interaction_2D;
                }
                ImGui::SameLine();
                if (button_icon(
                        !controller.ortho_interaction_2D,
                        "3D",
                        "3D Orthographic Camera Interaction")) {
                    controller.ortho_interaction_2D = !controller.ortho_interaction_2D;
                }
                ImGui::SameLine();
            }
        }

        // Camera direction
        {
            if (button_icon(
                    cam.is_orthogonal_direction(Camera::Dir::TOP),
                    "Top",
                    "Top-Down View")) {
                cam.set_orthogonal_direction(Camera::Dir::TOP);
                changed = true;
            }
            ImGui::SameLine();

            if (button_icon(cam.is_orthogonal_direction(Camera::Dir::BOTTOM), "Down", "Up View")) {
                cam.set_orthogonal_direction(Camera::Dir::BOTTOM);
                changed = true;
            }
            ImGui::SameLine();

            if (button_icon(
                    cam.is_orthogonal_direction(Camera::Dir::FRONT),
                    "Front",
                    "Front View")) {
                cam.set_orthogonal_direction(Camera::Dir::FRONT);
                changed = true;
            }
            ImGui::SameLine();

            if (button_icon(cam.is_orthogonal_direction(Camera::Dir::LEFT), "Left", "Left View")) {
                cam.set_orthogonal_direction(Camera::Dir::LEFT);
                changed = true;
            }
            ImGui::SameLine();

            if (button_icon(cam.is_orthogonal_direction(Camera::Dir::BACK), "Back", "Back View")) {
                cam.set_orthogonal_direction(Camera::Dir::BACK);
                changed = true;
            }
            ImGui::SameLine();

            if (button_icon(
                    cam.is_orthogonal_direction(Camera::Dir::RIGHT),
                    "Right",
                    "Right View")) {
                cam.set_orthogonal_direction(Camera::Dir::RIGHT);
                changed = true;
            }
            ImGui::SameLine();
        }

        auto view = registry.view<CameraController, Camera>();

        for (auto e : view) {
            if (changed)
                ui::publish<CameraChangedEvent>(registry, e);
        }

        // Multi viewport
        {
            if (button_icon(false, ICON_FA_SHARE_SQUARE, "Instance camera to other viewports")) {
                instance_camera_to_viewports(registry, viewport.camera_reference);
            }
            ImGui::SameLine();

            if (button_icon(false, ICON_FA_SHARE, "Copy camera to other viewports")) {
                copy_camera_to_viewports(registry, viewport.camera_reference);
            }
            ImGui::SameLine();
        }

        {
            bool fit = false;
            bool focus = false;
            if (button_icon(
                    false,
                    ICON_FA_COMPRESS_ARROWS_ALT,
                    "Focus On Selection",
                    "global.camera.center_on_selection",
                    &keys)) {
                focus = true;
            }
            ImGui::SameLine();

            if (button_icon(
                    false,
                    ICON_FA_EXPAND,
                    "Zoom To Fit Selection",
                    "global.camera.zoom_to_fit",
                    &keys)) {
                fit = true;
                focus = true;
            }

            if ((fit || focus) && registry.valid(viewport.camera_reference)) {
                camera_focus_and_fit(
                    registry,
                    viewport.camera_reference,
                    focus,
                    fit,
                    1.0f,
                    [](Registry& r, Entity e) { return is_selected(r, e); });
            }

            ImGui::SameLine();
        }

        if (button_icon(!controller.fov_zoom, ICON_FA_ARROWS_ALT_V, "Dolly")) {
            controller.fov_zoom = !controller.fov_zoom;
        }

        ImGui::SameLine();

        separator();

        if (button_icon(controller.auto_nearfar, ICON_FA_COMPRESS, "Automatic Clipping Planes")) {
            controller.auto_nearfar = !controller.auto_nearfar;
        }

        ImGui::SameLine();

        separator();
    }

#ifdef LGUI_RENDERER_DEPRECATED
    /*
        Ground rendering
    */
    if (viewport.renderer) {
        auto& renderer = *viewport.renderer;
        bool ground_pass = is_render_pass_enabled(viewport, default_render_pass_name<GroundPass>());
        if (button(ground_pass, ICON_FA_TH, "Toggle Ground")) {
            enable_render_pass(viewport, default_render_pass_name<GroundPass>(), !ground_pass);
        }

        ImGui::SameLine();

        // Ground options
        {
            ImGui::PushID("groundopt");
            if (ImGui::Button(ICON_FA_CARET_DOWN)) {
                ImGui::OpenPopup("Ground");
            }
            ImGui::SameLine();

            if (ImGui::BeginPopupContextItem("Ground")) {
                ImGui::Dummy(ImVec2(400, 0));
                UIWidget("Grid Options")(
                    renderer.get_default_pass<DefaultPasses::PASS_GROUND>()->get_options(),
                    "",
                    0,
                    false);

                ImGui::EndPopup();
            }

            ImGui::PopID();
        }

        separator();
    }
#endif

    draw_framebuffer_popup(registry, data);

    separator();

    ImGui::Dummy(ImVec2(0, 0));
}

void draw_viewport_texture(ViewportComponent& viewport)
{
    Texture* texture = nullptr;
    if (viewport.fbo->has_color_attachment()) {
        texture = viewport.fbo->get_color_attachement(0).get();
    } else if (viewport.fbo->has_depth_attachement()) {
        texture = viewport.fbo->get_depth_attachment().get();
    }
    if (!texture) {
        ImGui::Text("No framebuffer attachement");
        return;
    }

    draw_imgui_gl_texture(texture->get_id(), viewport.width, viewport.height);
}

void viewport_panel_system(Registry& registry, Entity e)
{
    ViewportPanel& data = registry.get<ViewportPanel>(e);
    auto& input = get_input(registry);
    if (!registry.valid(data.viewport) || !registry.has<ViewportComponent>(data.viewport)) {
        ImGui::Text("Invalid viewport");
        return;
    }
    auto& viewport = registry.get<ViewportComponent>(data.viewport);

    // Update FocusedViewportPanel
    if (registry.get<UIPanel>(e).is_focused) {
        registry.ctx<FocusedViewportPanel>().viewport_panel = e;
    }

    Camera& cam = get_viewport_camera(registry, viewport);

    ImGui::PushID(int(e));

    // Draw render pass popup
    draw_render_pass_popup(registry, data);

    // Draw toolbar
    if (data.show_viewport_toolbar) {
        draw_viewport_toolbar(registry, data);
    }

    {
        NoPadding _;
        // Look at current imgui state
        data.canvas_origin = ImGui::GetCursorScreenPos();
        data.available_width = std::max(16, static_cast<int>(ImGui::GetContentRegionAvail().x));
        data.available_height =
            std::max(16, static_cast<int>(ImGui::GetContentRegionAvail().y - 2));

        // Update viewport dimensions
        viewport.width = data.available_width;
        viewport.height = data.available_height;

        // Update camera dimensions (needed in camera controller)
        // TODO: camera controller shouldn't care about pixels
        cam.set_window_dimensions(float(viewport.width), float(viewport.height));

        // Draw the canvas/texture
        draw_viewport_texture(viewport);
    }

    // Compute mouse state
    data.hovered = ImGui::IsWindowHovered(ImGuiHoveredFlags_RootWindow) &&
                   data.is_over_viewport(input.mouse_position);
    data.mouse_in_canvas = data.screen_to_viewport(input.mouse_position);

    if (!registry.valid(viewport.camera_reference) ||
        !registry.has<CameraController>(viewport.camera_reference)) {
        ImGui::PopID();
        return;
    }

    CameraController& controller = registry.get<CameraController>(viewport.camera_reference);
    auto& keys = *input.keybinds;

    // If this viewport has focus, set draw list for gizmo here
    if (e == registry.ctx<FocusedViewportPanel>().viewport_panel) {
        gizmo_system_set_draw_list();
    }

    // Check for gizmo system being used by Tools
    bool hovered_no_gizmo = data.hovered && !gizmo_system_is_using() && !gizmo_system_is_over();

    if (hovered_no_gizmo) {
        if (keys.is_pressed("viewport.camera.rotate")) {
            if (!controller.rotation_active) {
                controller.rotation_mouse_start = data.mouse_in_canvas;
                controller.rotation_camera_pos_start = cam.get_position();
                controller.rotation_camera_up_start = cam.get_up();
            }
            controller.rotation_active = true;
        }

        // Zoom using mousewheel
        if (input.mouse_wheel != 0.0f) {
            controller.dolly_active = true;
            controller.dolly_delta = static_cast<float>(0.15f * input.mouse_wheel);
        } else {
            controller.dolly_active = false;
        }

        // Zoom using dolly keybind
        if (keys.is_down("viewport.camera.dolly")) {
            controller.dolly_active = true;
            controller.dolly_delta = float(input.mouse_delta.x()) / cam.get_window_width();
        }

        if (keys.is_down("viewport.camera.pan")) {
            controller.pan_active = true;
        }
    }

    if (keys.is_released("viewport.camera.rotate")) {
        controller.rotation_active = false;
    }

    if (keys.is_released("viewport.camera.dolly")) {
        controller.dolly_active = false;
    }

    if (keys.is_released("viewport.camera.pan")) {
        controller.pan_active = false;
    }

    controller.mouse_current = data.mouse_in_canvas;
    controller.mouse_delta = input.mouse_delta;

    ImGui::PopID();
}

} // namespace

bool ViewportPanel::is_over_viewport(const Eigen::Vector2f& pos) const
{
    return pos.x() > canvas_origin.x() && pos.y() > canvas_origin.y() &&
           pos.x() < canvas_origin.x() + available_width &&
           pos.y() < canvas_origin.y() + available_height;
}

Eigen::Vector2f ViewportPanel::screen_to_viewport(const Eigen::Vector2f& pos) const

Eigen::Vector2f ViewportPanel::viewport_to_screen(const Eigen::Vector2f& viewport_pos) const
{
    return {
        viewport_pos.x() + canvas_origin.x(),
        canvas_origin.y() + available_height - viewport_pos.y()};
}

Entity add_viewport_panel(Registry& r, const std::string& name /*= "Viewport"*/, Entity viewport)
{
    auto e = add_panel(r, name, viewport_panel_system);
    ViewportPanel vw;
    vw.viewport = viewport;
    r.emplace<ViewportPanel>(e, std::move(vw));
    return e;
}

} // namespace ui
} // namespace lagrange