#include "enjTelnetPanel.h"
#include <wx/spinctrl.h>
#include <wx/statline.h>
#include <wx/valgen.h>
#include "wx/fileconf.h"
#include "wx/wfstream.h"
#include <wx/filename.h>

#if wxUSE_FILEDLG
    #include "wx/filedlg.h"
#endif // wxUSE_FILEDLG

/*!
 * Control creation for PersonalRecordDialog
 */

BEGIN_EVENT_TABLE(PersonalRecordDialog, wxDialog)
END_EVENT_TABLE()

IMPLEMENT_CLASS(PersonalRecordDialog,wxDialog)

PersonalRecordDialog::PersonalRecordDialog( SiteInfo *site,wxWindow* parent,
      wxWindowID id, 
      const wxString& caption, 
      const wxPoint& pos, 
      const wxSize& size, 
      long style )
	:wxDialog(parent,id,caption,pos,size,style)
{
	si = site;
	CreateControls();
}

void PersonalRecordDialog::CreateControls()
{
	int x_pos = 0;
	int y_pos = 0;
    wxBoxSizer* topSizer = new wxBoxSizer(wxVERTICAL);
	wxBoxSizer* horSizer;
	wxBoxSizer* verSizer;
	wxStaticBoxSizer *shorSizer;
	wxStaticBoxSizer *sverSizer;
    this->SetSizer(topSizer);

	//basic options
	sverSizer = new wxStaticBoxSizer(
    new wxStaticBox( this, wxID_ANY,
        wxT("Please enter server by name or IP address"), wxDefaultPosition, wxSize(300,-1), 0 ),wxVERTICAL);
	topSizer->Add(sverSizer,0,wxALL,0);

	//server name and port num
	horSizer = new wxBoxSizer(wxHORIZONTAL);
	sverSizer->Add(horSizer,0,wxALL,0);

	horSizer->Add(
	 	new wxStaticText( this, wxID_STATIC,
        	wxT("Server:"), wxDefaultPosition, wxSize(50,-1) ),
	 	0,wxALL,0
	 );
//	nameCtrl = new wxTextCtrl ( this, wxID_ANY, wxEmptyString, wxDefaultPosition, wxSize(200,-1) );
	nameCtrl =	new wxComboBox(this, wxID_ANY ,wxEmptyString , 
					wxDefaultPosition, 
					wxSize(200,-1),
					0,NULL,
				   	wxCB_SORT);
	horSizer->Add( nameCtrl,0,wxALL,0);
	wxFileName fn(wxString(wxTheApp->argv[0]));
	wxString his_list(fn.GetPath() + "/history.servers");
	
	{//load history file into combobox
   		 bool success = false;
   		 wxFile file(his_list, wxFile::read);

   		 if (file.IsOpened())
   		 {
   		     wxString contents;
   		     // get the file size (assume it is not huge file...)
   		     ssize_t len = (ssize_t)file.Length();

   		     if (len > 0)
   		     {
   		         wxString buffer;
   		         success = (file.Read(wxStringBuffer(buffer, len), len) == len);
   		         contents = buffer;
				 while(buffer.Find('\n') != -1){
					int pos = buffer.Find('\n');
					wxString a_line(buffer.Mid(0,pos));
					a_line.Replace("\n","");
					int pos_1 = a_line.Find("://") ;
					if ( pos_1 != -1 ) {
						a_line.Remove(0,pos_1+3);
					}
					pos_1 = a_line.Find(":");
					if ( pos_1 != -1 ) {
						a_line.Truncate(pos_1);
					}
					if (a_line.Len() != 0 ) {
						if ( nameCtrl->FindString(a_line) == wxNOT_FOUND ) {
							nameCtrl->Append(a_line);
						}
					}
					buffer.Remove(0,pos+1);
				 }
   		     }
   		 }
	}

	horSizer->Add(5,5);
	horSizer->Add(
	 	new wxStaticText( this, wxID_STATIC,
        	wxT("Port:"), wxDefaultPosition, wxSize(40,-1) ),
	 	0,wxALL,0
	 );

	portCtrl = new wxTextCtrl ( this, wxID_ANY, wxEmptyString, wxDefaultPosition,
 wxSize(60,-1) );
	horSizer->Add( portCtrl,0,wxALL,0);

	//protocol
	sverSizer->Add(5,5);
	sverSizer->Add(
	 	new wxStaticText( this, wxID_STATIC,
        	wxT("Protocol:"), wxDefaultPosition, wxDefaultSize ),
	 	0,wxALL,0
	 );

	horSizer = new wxBoxSizer(wxHORIZONTAL);
	sverSizer->Add(horSizer,0,wxALL,0);

	horSizer->Add(50,5);
	telnetRa_id = wxNewId();
    telnetRa = new wxRadioButton( this, telnetRa_id, _T("Telnet"), wxDefaultPosition, wxSize(100,-1), wxRB_GROUP );
    telnetRa->SetValue( false );
	horSizer->Add(telnetRa,0,wxALL,0);
	Connect(telnetRa_id,wxEVT_COMMAND_RADIOBUTTON_SELECTED,
		wxCommandEventHandler(PersonalRecordDialog::OnTelnetRaButton));
	

	sshRa_id = wxNewId();
    sshRa = new wxRadioButton( this, sshRa_id, _T("SSH"), wxDefaultPosition, wxSize(100,-1) ),
	Connect(sshRa_id,wxEVT_COMMAND_RADIOBUTTON_SELECTED,
		wxCommandEventHandler(PersonalRecordDialog::OnSSHRaButton));
	horSizer->Add( sshRa,0,wxALL,0);

	shellRa_id = wxNewId();
    shellRa = new wxRadioButton( this, shellRa_id, _T("Shell"), wxDefaultPosition, wxSize(100,-1) ),
	Connect(shellRa_id,wxEVT_COMMAND_RADIOBUTTON_SELECTED,
		wxCommandEventHandler(PersonalRecordDialog::OnShellRaButton));
	horSizer->Add( shellRa,0,wxALL,0);


	//end basic options	

	//ssh related option
	sverSizer = new wxStaticBoxSizer(
    	new wxStaticBox( this, wxID_ANY,
        	wxT("SSH"), wxDefaultPosition, wxSize(300,-1), 0 ),
		wxVERTICAL);
	//sverSizer->SetMinSize(300,-1);
	topSizer->Add(sverSizer,0,wxALL,0);

	verSizer = new wxBoxSizer(wxVERTICAL);
	sverSizer->Add(verSizer,0,wxALL,0);

	verSizer->Add(
	 	new wxStaticText( this, wxID_STATIC,
        	wxT("Private key file for authentication:"), wxDefaultPosition, wxDefaultSize ),
	 	0,wxALL,0
	 );
	verSizer->Add(5,2);
	horSizer = new wxBoxSizer(wxHORIZONTAL);
	verSizer->Add(horSizer,0,wxALL,0);

	sshPrivateKeyFileCtrl =new wxTextCtrl ( this, wxID_ANY, wxEmptyString, wxDefaultPosition, wxSize(250,-1) ),
	horSizer->Add(sshPrivateKeyFileCtrl, 0,wxALL,0);
	horSizer->Add(5,5);
	browser_id = wxNewId();
	horSizer->Add(
		new wxButton ( this, browser_id, wxT("&Browser..."),
        wxDefaultPosition, wxSize(100,-1), 0 ),
	 	0,wxALL,0
	 );
	Connect(browser_id,wxEVT_COMMAND_BUTTON_CLICKED,
		wxCommandEventHandler(PersonalRecordDialog::OnBrowserButton));
	//ssh end
	

	topSizer->Add(10,10);    
	wxStaticLine* line = new wxStaticLine ( this, wxID_STATIC,
        wxDefaultPosition, wxDefaultSize, wxLI_HORIZONTAL );
	topSizer->Add(line,0,wxEXPAND,5);


	horSizer = new wxBoxSizer(wxHORIZONTAL);
	horSizer->Add(100,10);
    // The OK button
	topSizer->Add(horSizer);
    wxButton* ok = 
			new wxButton ( this, wxID_OK, wxT("&OK"),
        wxDefaultPosition, wxDefaultSize, 0 );
	horSizer->Add(ok,0,wxALIGN_CENTER_HORIZONTAL|wxALL,5);

    // The Cancel button

    wxButton* cancel = new wxButton ( this, wxID_CANCEL,
				   	wxT("&Cancel"), wxDefaultPosition, wxDefaultSize, 0 );
	horSizer->Add(cancel,0,wxALIGN_CENTER_HORIZONTAL|wxALL,5);
	Fit();
}

#if 0
	wxStaticBox *label = new wxStaticText( this, wxID_STATIC,
        wxT("Protocol"), wxPoint(10,10), wxDefaultSize, 0 );
    boxSizer->Add(descr, 0, wxALIGN_LEFT|wxALL, 5);

    // A top-level sizer

    // A second box sizer to give more space around the controls

    wxBoxSizer* boxSizer = new wxBoxSizer(wxVERTICAL);
    topSizer->Add(boxSizer, 0, wxALIGN_CENTER_HORIZONTAL|wxALL, 5);

    // A friendly message

    boxSizer->Add(descr, 0, wxALIGN_LEFT|wxALL, 5);

    // Spacer
    boxSizer->Add(5, 5, 0, wxALIGN_CENTER_HORIZONTAL|wxALL, 5);


    // A horizontal box sizer to contain age, sex and vote

    wxBoxSizer* ageSexVoteBox = new wxBoxSizer(wxHORIZONTAL);
    boxSizer->Add(ageSexVoteBox, 0, wxGROW|wxALL, 5);

    // Label for the age control
/*
    wxStaticText* ageLabel = new wxStaticText ( this, wxID_STATIC,
        wxT("&Age:"), wxDefaultPosition, wxDefaultSize, 0 );
    ageSexVoteBox->Add(ageLabel, 0, wxALIGN_CENTER_VERTICAL|wxALL, 5);
	*/

    // A spin control for the user's age
/*
    ageSpin = new wxSpinCtrl ( this, wxID_ANY,
        wxEmptyString, wxDefaultPosition, wxSize(60, -1),
        wxSP_ARROW_KEYS, 0, 120, 25 );
    ageSexVoteBox->Add(ageSpin, 0, wxALIGN_CENTER_VERTICAL|wxALL, 5);
*/
    // Label for the sex control
    wxStaticText* sexLabel = new wxStaticText ( this, wxID_STATIC,
        wxT("&Protocol:"), wxDefaultPosition, wxDefaultSize, 0 );
    ageSexVoteBox->Add(sexLabel, 0, wxALL, 5);

    // Create the sex choice control
    wxString sexStrings[] = {
        wxT("Telnet"),
        wxT("SSH")
    };

    sexChoice = new wxChoice ( this, wxID_ANY,
        wxDefaultPosition, wxSize(80, -1), WXSIZEOF(sexStrings),
            sexStrings, 0 );
    //sexChoice->SetStringSelection(wxT("Female"));
    ageSexVoteBox->Add(sexChoice, 0, wxALL, 5);


    // Label for the name text control
    wxStaticText* portLabel = new wxStaticText ( this, wxID_STATIC,
        wxT("&Server Name:"), wxDefaultPosition,wxDefaultSize , 0 );
    ageSexVoteBox->Add(portLabel, 0, wxALL, 5);

    // A text control for the user's name

    nameCtrl = new wxTextCtrl ( this, wxID_ANY, wxT("Emma"), wxDefaultPosition,
 wxSize(200,-1), 0 );
    ageSexVoteBox->Add(nameCtrl, 0, wxGROW|wxALL, 5);


    // Label for the name text control
    wxStaticText* nameLabel = new wxStaticText ( this, wxID_STATIC,
        wxT("&Port:"), wxDefaultPosition,wxDefaultSize , 0 );
    ageSexVoteBox->Add(nameLabel, 0, wxALIGN_LEFT|wxALL, 5);

    // A text control for the user's name
    wxTextCtrl *portCtrl = new wxTextCtrl ( this, wxID_ANY, wxT("Emma"), wxDefaultPosition,
 wxSize(100,-1), 0 );
    ageSexVoteBox->Add(portCtrl, 0, wxGROW|wxALL, 5);
	
/*
    // Add a spacer that stretches to push the Vote control
    // to the right

    ageSexVoteBox->Add(5, 5, 1, wxALIGN_CENTER_VERTICAL|wxALL, 5);

    voteCheckBox = new wxCheckBox( this, wxID_ANY,
       wxT("&Vote"), wxDefaultPosition, wxDefaultSize, 0 );
    voteCheckBox ->SetValue(true);
    ageSexVoteBox->Add(voteCheckBox, 0,
        wxALIGN_CENTER_VERTICAL|wxALL, 5);
*/
    // A dividing line before the OK and Cancel buttons

    wxStaticLine* line = new wxStaticLine ( this, wxID_STATIC,
        wxDefaultPosition, wxDefaultSize, wxLI_HORIZONTAL );
    boxSizer->Add(line, 0, wxGROW|wxALL, 5);

    // A horizontal box sizer to contain Reset, OK, Cancel and Help

    wxBoxSizer* okCancelBox = new wxBoxSizer(wxHORIZONTAL);
    boxSizer->Add(okCancelBox, 0, wxALIGN_CENTER_HORIZONTAL|wxALL, 5);

    // The Reset button

    // The OK button

    wxButton* ok = new wxButton ( this, wxID_OK, wxT("&OK"),
        wxDefaultPosition, wxDefaultSize, 0 );
    okCancelBox->Add(ok, 0, wxALIGN_CENTER_VERTICAL|wxALL, 5);

    // The Cancel button

    wxButton* cancel = new wxButton ( this, wxID_CANCEL,
        wxT("&Cancel"), wxDefaultPosition, wxDefaultSize, 0 );
    okCancelBox->Add(cancel, 0, wxALIGN_CENTER_VERTICAL|wxALL, 5);

	/*
    // The Help button

    wxButton* help = new wxButton( this, wxID_HELP, wxT("&Help"),
        wxDefaultPosition, wxDefaultSize, 0 );
    okCancelBox->Add(help, 0, wxALIGN_CENTER_VERTICAL|wxALL, 5);
	*/
	SetSize(800,600);
	SetAutoLayout(true);
	Layout();
#endif

/*!
 * Transfer data to the window
 */

bool PersonalRecordDialog::TransferDataToWindow()
{
	/*
    wxTextCtrl* nameCtrl = (wxTextCtrl*) FindWindow(ID_NAME);
    wxSpinCtrl* ageCtrl = (wxSpinCtrl*) FindWindow(ID_SAGE);
    wxChoice* sexCtrl = (wxChoice*) FindWindow(ID_SEX);
    wxCheckBox* voteCtrl = (wxCheckBox*) FindWindow(ID_VOTE);

    nameCtrl->SetValue(m_name);
    ageCtrl->SetValue(m_age);
    sexCtrl->SetSelection(m_sex);
    voteCtrl->SetValue(m_vote);
	*/
	portCtrl->SetValue(wxString::Format("%d",si->port));
	if ( si->protocol == SOCK_SSH ) {
		sshRa->SetValue(true);
	}else if ( si->protocol == SOCK_TELNET ) {
		telnetRa->SetValue(true);
	}else if ( si->protocol == SOCK_EXECMD ) {
		shellRa->SetValue(true);
	}
//    nameCtrl->SetValue(m_name);
  //  ageSpin->SetValue(m_age);
 //   sexChoice->SetSelection(m_sex);
  //  voteCheckBox->SetValue(m_vote);

    return true;
}

/*!
 * Transfer data from the window
 */

bool PersonalRecordDialog::TransferDataFromWindow()
{
	si->ip = nameCtrl->GetValue();
	long portint = 0;
	if ( (portCtrl->GetValue()).ToLong(&portint) ){
		si->port=portint;
	}else{
		si->port=-1;
	}

	if ( telnetRa->GetValue()) {
		si->protocol = SOCK_TELNET;
	}else if ( sshRa->GetValue()) {
		si->protocol = SOCK_SSH;
	}else if ( shellRa->GetValue()){
		si->protocol = SOCK_EXECMD ;
	}else {
		si->protocol = SOCK_UNKNOWN;
	}

	si->keyfile=sshPrivateKeyFileCtrl->GetValue();

		
    return true;
}

void PersonalRecordDialog::OnBrowserButton(wxCommandEvent &event)
{
    static wxString s_extDef;
    wxString path = wxFileSelector(
                                    _T("Select the file to load"),
                                    wxEmptyString, wxEmptyString,
                                    s_extDef,
                                    wxString::Format
                                    (
                                        _T("PuTTY Private Key Files (*.ppk)|*.ppk|All files (%s)|%s"),
                                        wxFileSelectorDefaultWildcardStr,
                                        wxFileSelectorDefaultWildcardStr
									 
                                    ),
                                    wxCHANGE_DIR,
                                    this
                                   );

    if ( !path )
        return;

    // it is just a sample, would use wxSplitPath in real program
    s_extDef = path.AfterLast(_T('.'));
	sshPrivateKeyFileCtrl->SetValue(path);
    wxLogMessage(_T("You selected the file '%s', remembered extension '%s'"),
                 (const wxChar*) path, (const wxChar*) s_extDef);
}

void PersonalRecordDialog::OnTelnetRaButton(wxCommandEvent &event)
{
	portCtrl->Enable();
	portCtrl->SetValue(wxString::Format("%d",TELNET_DEFAULT_PORT));
}

void PersonalRecordDialog::OnSSHRaButton(wxCommandEvent &event)
{
	portCtrl->Enable();
	portCtrl->SetValue(wxString::Format("%d",SSH_DEFAULT_PORT));
}

void PersonalRecordDialog::OnShellRaButton(wxCommandEvent &event)
{
	portCtrl->Disable();
	//portCtrl->SetValue(wxString::Format("%d",SSH_DEFAULT_PORT));
}




