#include <siaapi.h>
#include <regex>
#include <siadriveconfig.h>

using namespace Sia::Api;

CSiaApi::CSiaApi(CSiaDriveConfig* siaDriveConfig) :
	_siaDriveConfig(siaDriveConfig),
	_wallet(new CSiaWallet(siaDriveConfig)),
	_renter(new CSiaRenter(siaDriveConfig)),
	_consensus(new CSiaConsensus(siaDriveConfig)),
  _hostDb(new CSiaHostDb(siaDriveConfig)),
  _refreshThread(new CAutoThread(siaDriveConfig, [this] (CSiaDriveConfig* siaDriveConfig) { this->Refresh( ); }))
{
}

CSiaApi::~CSiaApi()
{
  _refreshThread->StopAutoThread();
}

void CSiaApi::Refresh( )
{
  this->_consensus->Refresh();
  this->_renter->Refresh();
  this->_hostDb->Refresh();
  // Initialize last - wallet contains connection status
  this->_wallet->Refresh();
}

SString CSiaApi::FormatToSiaPath(SString path)
{
	if (path.Length())
	{
		std::replace(path.begin(), path.end(), '\\', '/');
		std::wregex r(L"/+");
		path = std::regex_replace(path.str(), r, L"/");

		while (path[0] == '/')
		{
			path = path.SubString(1);
		}
	}
	else
	{
		path = L"/";
	}
	

	return path;
}

void CSiaApi::StartBackgroundRefresh()
{
  _refreshThread->StartAutoThread();
}

void CSiaApi::StopBackgroundRefresh()
{
  _refreshThread->StopAutoThread();
}

SString CSiaApi::GetServerVersion() const
{
	return CSiaCurl(_siaDriveConfig->GetHostConfig()).GetServerVersion();
}

CSiaWalletPtr CSiaApi::GetWallet() const
{
	return _wallet;
}

CSiaRenterPtr CSiaApi::GetRenter() const
{
	return _renter;
}

CSiaConsensusPtr CSiaApi::GetConsensus() const
{
	return _consensus;
}

CSiaHostDbPtr CSiaApi::GetHostDb() const
{
  return _hostDb;
}