#include "configdialog.h"

//(*InternalHeaders(configdialog)
#include <wx/bitmap.h>
#include <wx/button.h>
#include <wx/font.h>
#include <wx/image.h>
#include <wx/intl.h>
#include <wx/string.h>
//*)

//(*IdInit(configdialog)
const long configdialog::ID_STATICBITMAP1 = wxNewId();
const long configdialog::ID_STATICTEXT2 = wxNewId();
const long configdialog::ID_STATICTEXT3 = wxNewId();
const long configdialog::ID_STATICTEXT1 = wxNewId();
const long configdialog::ID_HYPERLINKCTRL2 = wxNewId();
const long configdialog::ID_HYPERLINKCTRL1 = wxNewId();
//*)

BEGIN_EVENT_TABLE(configdialog,wxDialog)
	//(*EventTable(configdialog)
	//*)
END_EVENT_TABLE()

bool fileExists(const std::string &fileName) {
  return std::ifstream(fileName.c_str()).good();
}

void configdialog::OnQuit(wxCommandEvent& event)
{
    Close(TRUE);
}

std::string configdialog::utf8_encode(const std::wstring &wstr)
{
    if( wstr.empty() ) return std::string();
    int size_needed = WideCharToMultiByte(CP_UTF8, 0, &wstr[0], (int)wstr.size(), NULL, 0, NULL, NULL);
    std::string strTo( size_needed, 0 );
    WideCharToMultiByte                  (CP_UTF8, 0, &wstr[0], (int)wstr.size(), &strTo[0], size_needed, NULL, NULL);
    return strTo;
}

std::wstring getSNFFilePath() {                                                // Get the config file path.
	std::wstring install_pathW;
	HKEY hKey;
	WCHAR szBuffer[512];
	DWORD dwBufferSize = sizeof(szBuffer);
	std::wstring regValue = L"";

	if (ERROR_SUCCESS == RegOpenKeyEx(HKEY_LOCAL_MACHINE, L"SOFTWARE\\Alt-N Technologies\\MDaemon", 0, KEY_READ, &hKey)){
		if(ERROR_SUCCESS == RegQueryValueEx(hKey, (LPCWSTR) L"AppPath", NULL, NULL, (LPBYTE) &szBuffer, &dwBufferSize)){
			RegCloseKey(hKey);
			regValue = std::wstring(szBuffer);
			std::wstring termCheck;
			for(auto val: regValue){
				if(val != L'\0'){
					termCheck += val;
				}
			}
			if(termCheck.size() == 512){
				regValue = L""; // RegValue wasn't null terminated
			}
			else{
				int PathEnd = regValue.length();                                       // Grab the length.
				if(PathEnd > 0) { regValue.erase(PathEnd-1,1); }                       // Eat the stroke at the end.
				PathEnd = regValue.find_last_of(L"\\");                                 // Find the next stroke in.
				int PathLength = regValue.length();                                    // Grab the path length.
				int EraseSpan = PathLength - (PathEnd+1);                               // Calculate the amount to erase.
				regValue.erase(PathEnd+1,EraseSpan);                                   // Erase it to get the root path.
				regValue.append(L"SNF\\");
			}
		}
	}
    // Return either the empty string or the configuration file path.
    return regValue;                                                           // Return what we have.
}


configdialog::configdialog(wxWindow* parent,wxWindowID id)
{
	install_path = utf8_encode(getSNFFilePath());
	wxBitmap logo = wxNullBitmap;
	std::string image_loc = install_path + "\\logo.png";
	if(fileExists(image_loc)){
		logo = wxBitmap(wxImage(image_loc));
	}
	//(*Initialize(configdialog)
	wxFlexGridSizer* FlexGridSizer10;
	wxFlexGridSizer* FlexGridSizer1;
	wxFlexGridSizer* FlexGridSizer2;
	wxFlexGridSizer* FlexGridSizer3;
	wxFlexGridSizer* FlexGridSizer4;
	wxFlexGridSizer* FlexGridSizer5;
	wxFlexGridSizer* FlexGridSizer6;
	wxFlexGridSizer* FlexGridSizer7;
	wxFlexGridSizer* FlexGridSizer8;
	wxFlexGridSizer* FlexGridSizer9;
	wxStdDialogButtonSizer* StdDialogButtonSizer1;

	Create(parent, wxID_ANY, _("SNF Configuration"), wxDefaultPosition, wxDefaultSize, wxSTAY_ON_TOP|wxCAPTION|wxDEFAULT_DIALOG_STYLE|wxSYSTEM_MENU|wxCLOSE_BOX|wxTAB_TRAVERSAL, _T("wxID_ANY"));
	SetFocus();
	FlexGridSizer1 = new wxFlexGridSizer(6, 1, 1, 1);
	FlexGridSizer6 = new wxFlexGridSizer(0, 2, 0, 0);
	FlexGridSizer7 = new wxFlexGridSizer(0, 3, 0, 0);
	StaticBitmap1 = new wxStaticBitmap(this, ID_STATICBITMAP1, logo, wxDefaultPosition, wxDefaultSize, wxNO_BORDER, _T("ID_STATICBITMAP1"));
	FlexGridSizer7->Add(StaticBitmap1, 1, wxALIGN_CENTER_HORIZONTAL|wxALIGN_CENTER_VERTICAL, 5);
	FlexGridSizer6->Add(FlexGridSizer7, 1, wxALL|wxALIGN_CENTER_HORIZONTAL|wxALIGN_CENTER_VERTICAL, 5);
	FlexGridSizer1->Add(FlexGridSizer6, 1, wxALL|wxALIGN_CENTER_HORIZONTAL|wxALIGN_CENTER_VERTICAL, 5);
	FlexGridSizer8 = new wxFlexGridSizer(3, 1, 0, 0);
	StaticText2 = new wxStaticText(this, ID_STATICTEXT2, _("SNF MDaemon Plugin Version 4.0"), wxDefaultPosition, wxDefaultSize, 0, _T("ID_STATICTEXT2"));
	wxFont StaticText2Font(12,wxFONTFAMILY_SWISS,wxFONTSTYLE_NORMAL,wxFONTWEIGHT_BOLD,false,_T("Arial"),wxFONTENCODING_DEFAULT);
	StaticText2->SetFont(StaticText2Font);
	FlexGridSizer8->Add(StaticText2, 1, wxALL|wxALIGN_CENTER_HORIZONTAL|wxALIGN_CENTER_VERTICAL, 5);
	FlexGridSizer9 = new wxFlexGridSizer(0, 3, 0, 0);
	StaticText3 = new wxStaticText(this, ID_STATICTEXT3, _("License ID: "), wxDefaultPosition, wxDefaultSize, 0, _T("ID_STATICTEXT3"));
	wxFont StaticText3Font(10,wxFONTFAMILY_SWISS,wxFONTSTYLE_NORMAL,wxFONTWEIGHT_BOLD,true,_T("Arial"),wxFONTENCODING_DEFAULT);
	StaticText3->SetFont(StaticText3Font);
	FlexGridSizer9->Add(StaticText3, 1, wxALL|wxALIGN_CENTER_HORIZONTAL|wxALIGN_CENTER_VERTICAL, 5);
	FlexGridSizer8->Add(FlexGridSizer9, 1, wxALL|wxALIGN_CENTER_HORIZONTAL|wxALIGN_CENTER_VERTICAL, 5);
	FlexGridSizer3 = new wxFlexGridSizer(0, 1, 0, 0);
	StaticText1 = new wxStaticText(this, ID_STATICTEXT1, _("\n   The full range of SNFServer features are provided by the plugin.\n   All of these can be configured in the MDaemon/SNF/snfmdplugin.xml file.\n\n   HOWEVER, some of the default settings are required in order\n   for the plugin to work properly with MDaemon.\n\n   In particular be careful about modifying <paths/> or <xheaders/>.\n"), wxDefaultPosition, wxDefaultSize, wxSUNKEN_BORDER, _T("ID_STATICTEXT1"));
	FlexGridSizer3->Add(StaticText1, 1, wxALL, 10);
	FlexGridSizer8->Add(FlexGridSizer3, 1, wxALL|wxALIGN_CENTER_HORIZONTAL|wxALIGN_CENTER_VERTICAL, 0);
	FlexGridSizer1->Add(FlexGridSizer8, 1, wxALL|wxALIGN_CENTER_HORIZONTAL|wxALIGN_CENTER_VERTICAL, 5);
	FlexGridSizer2 = new wxFlexGridSizer(3, 1, 0, 0);
	FlexGridSizer4 = new wxFlexGridSizer(0, 3, 0, 0);
	HyperlinkCtrl2 = new wxHyperlinkCtrl(this, ID_HYPERLINKCTRL2, _("Click here to view your configuration file."), wxEmptyString, wxDefaultPosition, wxDefaultSize, wxHL_CONTEXTMENU|wxHL_ALIGN_CENTRE|wxNO_BORDER, _T("ID_HYPERLINKCTRL2"));
	FlexGridSizer4->Add(HyperlinkCtrl2, 1, wxALL|wxALIGN_CENTER_HORIZONTAL|wxALIGN_CENTER_VERTICAL, 5);
	FlexGridSizer2->Add(FlexGridSizer4, 1, wxALL|wxALIGN_CENTER_HORIZONTAL|wxALIGN_CENTER_VERTICAL, 0);
	FlexGridSizer5 = new wxFlexGridSizer(0, 3, 0, 0);
	HyperlinkCtrl1 = new wxHyperlinkCtrl(this, ID_HYPERLINKCTRL1, _("Click here for more information."), _("https://www.armresearch.com/Documentation/QA/mdaemon_plugin-238282018.jsp"), wxDefaultPosition, wxDefaultSize, wxHL_CONTEXTMENU|wxHL_ALIGN_CENTRE|wxNO_BORDER, _T("ID_HYPERLINKCTRL1"));
	FlexGridSizer5->Add(HyperlinkCtrl1, 1, wxALL|wxALIGN_CENTER_HORIZONTAL|wxALIGN_CENTER_VERTICAL, 5);
	FlexGridSizer2->Add(FlexGridSizer5, 1, wxALL|wxALIGN_CENTER_HORIZONTAL|wxALIGN_CENTER_VERTICAL, 5);
	FlexGridSizer1->Add(FlexGridSizer2, 1, wxALL|wxALIGN_CENTER_HORIZONTAL|wxALIGN_CENTER_VERTICAL, 5);
	StdDialogButtonSizer1 = new wxStdDialogButtonSizer();
	StdDialogButtonSizer1->AddButton(new wxButton(this, wxID_OK, wxEmptyString));
	StdDialogButtonSizer1->Realize();
	FlexGridSizer1->Add(StdDialogButtonSizer1, 1, wxALL|wxALIGN_CENTER_HORIZONTAL|wxALIGN_CENTER_VERTICAL, 5);
	FlexGridSizer10 = new wxFlexGridSizer(0, 3, 0, 0);
	FlexGridSizer1->Add(FlexGridSizer10, 1, wxALL|wxALIGN_CENTER_HORIZONTAL|wxALIGN_CENTER_VERTICAL, 5);
	SetSizer(FlexGridSizer1);
	FlexGridSizer1->Fit(this);
	FlexGridSizer1->SetSizeHints(this);

	Connect(ID_HYPERLINKCTRL2,wxEVT_COMMAND_HYPERLINK,(wxObjectEventFunction)&configdialog::OnHyperlinkCtrl2Click);
	Connect(ID_HYPERLINKCTRL1,wxEVT_COMMAND_HYPERLINK,(wxObjectEventFunction)&configdialog::OnHyperlinkCtrl1Click);
	//*)

	//install_path = utf8_encode(install_pathW);
	std::string license_path = install_path + "\\identity.xml";
    if (fileExists(license_path)) {
    std::ifstream identity;                    // Grab the input file.
    identity.open(license_path.c_str(),              // Open it in binary mode
             std::ios::in | std::ios::binary);      // to avoid corruption issues.
    std::string line;
    std::string license_tag = "licenseid=\'";
    while (getline(identity, line))       // read in line
        {
            std::size_t found = line.find(license_tag);
            if (found!=std::string::npos){
                std::cout << "first 'needle' found at: " << found << '\n';
                StaticText3->SetLabel("License ID: " + line.substr(found+11, 8));
            }
        }
    }
}

configdialog::~configdialog()
{
	//(*Destroy(configdialog)
	//*)
}


void configdialog::OnHyperlinkCtrl1Click(wxCommandEvent& event)
{
    wxLaunchDefaultBrowser("https://www.armresearch.com/Documentation/QA/mdaemon_plugin-238282018.jsp");
}

void configdialog::OnHyperlinkCtrl2Click(wxCommandEvent& event)
{
    wxLaunchDefaultApplication(install_path + "\\snfmdplugin.xml");
}
