#include "stdafx.h"
#include "CApp.h"


CApp* SSingleton<CApp>::ms_Singleton = NULL;

CApp::CApp() : m_is_out(0), m_versioninfo(nullptr),m_userinfo(nullptr), m_server_list(nullptr), m_sys_config(nullptr), m_proxy_mode(PROXY_MODE::sys_mode), m_route_mode(ROUT_MODE::cn_mode)
{
	m_hInst = nullptr;
}

CApp::~CApp()
{
	UnInit();
}

void CApp::Init()
{
	if (!m_userinfo)
	{
		m_userinfo = new CUserInfo();
	}
	if (!m_server_list)
	{
		m_server_list = new CServerList();
	}
 
	if (!m_versioninfo)
	{
		m_versioninfo = new CVersion();
	}
	
	if (!m_sys_config)
	{
		m_sys_config = new CSysConfig();
	}
}

void CApp::UnInit() {
	if (m_userinfo)
	{
		delete m_userinfo;
		m_userinfo = nullptr;
	}
	if (m_server_list)
	{
		delete m_server_list;
		m_server_list = nullptr;
	}
	
	if (m_versioninfo)
	{
		delete m_versioninfo;
		m_versioninfo = nullptr;
	}

	if (m_sys_config)
	{
		delete m_sys_config;
		m_sys_config = nullptr;
	}
}

 
CUserInfo* CApp::GetUserinfo()
{
	return m_userinfo;
}

CServerList* CApp::GetServerList()
{
	return m_server_list;
}

CVersion* CApp::GetVerinfo()
{
	return m_versioninfo;
}

CSysConfig* CApp::GetSysconfig()
{
	return m_sys_config;
}

void CApp::SetOut(int out)
{
	m_is_out = out;
}

int CApp::GetOut()
{
	return m_is_out;
}

void CApp::SetSysMode(PROXY_MODE mode)
{
	m_proxy_mode = mode;
}

PROXY_MODE CApp::GetSysMode()
{
	return m_proxy_mode;
}

void CApp::SetRouteMode(ROUT_MODE mode)
{
	m_route_mode = mode;
}

ROUT_MODE CApp::GetRouteMode()
{
	return m_route_mode;
}

void CApp::SetMethod(HINSTANCE hinst)
{
	m_hInst = hinst;
}

HINSTANCE CApp::GetMethod()
{
	return m_hInst;
}

void CApp::ChkeAndSetDtaPath()
{
	std::wstring  portableDataPath = std::filesystem::current_path().wstring() + L"\\" + DSPROXY_DATA_DIR_PORTABLE;

	if (std::filesystem::is_directory(portableDataPath)) {
		m_dataPath = std::move(portableDataPath);
	}
	else {
		m_dataPath = GetKnownFolderFsPath(FOLDERID_RoamingAppData) / DSPROXY_DATA_DIR;
	}
	
	m_configPath = m_dataPath / DSPROXY_CONFIG_DIR_NAME;
	m_config_Gui_Path = m_dataPath;
}

bool CApp::CheckOnlyOneInstance() noexcept
{
	auto hFile = CreateFileW(m_dataPath.c_str(), GENERIC_WRITE, FILE_SHARE_READ, nullptr, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, nullptr);
	if (hFile == INVALID_HANDLE_VALUE && GetLastError() != ERROR_FILE_NOT_FOUND)
		return false;
	// Hold this handle
	return true;
}

std::filesystem::path CApp::GetDataPath()
{
	return m_dataPath;
}

std::filesystem::path CApp::GetConfigPath()
{
	return m_configPath;
}

std::filesystem::path CApp::GetConfigGuiPath()
{
	return m_config_Gui_Path;
}

void CApp::SetupDataDirectory()
{
	try
	{
		CreateDirectoryIgnoreExist(m_configPath.c_str());
		
	}
	CATCH_LOG();
}

void CApp::SetCLashRuning(bool m)
{
	m_clashRuning = m;
}

bool CApp::GetClashRuning()
{
	return m_clashRuning;
}

std::string CApp::GetSelect_node() const { return select_node; }

void CApp::SetSelect_node(std::string val) {
	select_node = val; 
}
 
