/*
 * <insert one-line description of what the program does>
 * Copyright (c) <2008-2009>, Intel Corporation.
 *
 * This program is free software; you can redistribute it and/or modify it
 * under the terms and conditions of the GNU Lesser General Public License,
 * version 2.1, as published by the Free Software Foundation.
 *
 * This program is distributed in the hope it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public License for
 * more details.
 *
 * You should have received a copy of the GNU Lesser General Public License along with
 * this program; if not, write to the Free Software Foundation, Inc., 
 * 51 Franklin St - Fifth Floor, Boston, MA 02110-1301 USA.
 *
 */
#include "GUI/FormTCAgent.h"
#include "gtk/gtkmain.h"
#include <time.h>
#include <pthread.h>
#include "GUI/macro.h"
#include "GUI/resmgmt.h"
#include "Engine/TCEngine.h"
#include "GUI/GUI.h"


/// <summary>
/// Alreadly download success once
/// </summary>
static bool m_bDownloaded;
//const int STATUS_DOWNLOADING = 10;

static int m_status;//normal,warning,urgency,downloading

/// <summary>
/// Warning already download once
/// </summary>
//static bool m_bWarningDownload;
/// <summary>
/// bShow reboot form
/// </summary>
bool m_bRebootForm = FALSE;


//four windows
extern GtkWidget *AgentWindow;
extern GtkWidget *RebootWindow;
extern GtkWidget *AboutWindow;

//resource manager
extern RESOURCE_MANAGER g_resManager;


guint32 m_autointerval = DEFAULT_HEARTBEAT_INTERVAL;//300000;
static int m_DownloadPushTimes=0;

static TCEngine tcEngine;


gint m_timer_autodownload;//download every 10 minutes
gint m_timer_pushdownload;//download push packet, download 10 times after reboot 


#define setlabeltext(window,name,text) (gtk_label_set_text((GtkLabel *)lookup_widget(GTK_WIDGET(window),name),text))
#define getlabeltext(window,name) (gtk_label_get_text((GtkLabel *)lookup_widget(GTK_WIDGET(window),name)))

#define setentrytext(window,name,text) (gtk_entry_set_text((GtkEntry *)lookup_widget(GTK_WIDGET(window),name),text))
#define getentrytext(window,name) (gtk_entry_get_text((GtkEntry *)lookup_widget(GTK_WIDGET(window),name)))


#define setbuttondisabled(window,name) (gtk_widget_set_sensitive(lookup_widget(GTK_WIDGET(window),name),FALSE))
#define setbuttonenabled(window,name) (gtk_widget_set_sensitive(lookup_widget(GTK_WIDGET(window),name),TRUE))
#define getbuttonstatus(window,name) (GTK_WIDGET_SENSITIVE(lookup_widget(GTK_WIDGET(window),name)))

#define setbuttontext(window,name,text) (gtk_button_set_label((GtkButton *)lookup_widget(GTK_WIDGET(window),name),text))

#define setcolor(window,name,color) (gtk_widget_modify_fg((GtkLabel *)lookup_widget(GTK_WIDGET(window),name),GTK_STATE_NORMAL,color))

#define setfocus(window,name) 
//#define setfocus(window,name) (GTK_WIDGET_SET_FLAGS(lookup_widget(GTK_WIDGET(window),name),GTK_HAS_FOCUS))


const int INFORMATION_MSGBOX = 0;
const int ERROR_MSGBOX = 1;
//const int WARNING_MSGBOX = 2;
///type=0,information
///type=1,error
int MSGBOX ( int type, char* title, char* msg)
{
	char cmd[MSG_MAX_LEN]="";
	if (title == NULL || msg == NULL) return 0;
	//kdialog --title "lalala" --msgbox "hiskdfajkdsf"
	strcpy(cmd, "kdialog  --caption \"");

//	if (strlen(title)>0)
//		strcat(cmd,title);
//	else
//		strcat(cmd,g_resManager.T_strTCAgentTitle);
	if (type==INFORMATION_MSGBOX)
		strcat(cmd, "\" --msgbox \"");
	else
		strcat(cmd, "\" --error \"");

	strcat(cmd,msg);
	strcat(cmd, "\"");
	system(cmd);
}

char*   trimleft(char*   str,   const   char*   pattern   /*=   "   \t"*/)   
  {   
  char* p   =   str;   
  char* endp   =   str   +   strlen(str);   
  while   (p   <   endp)   
  {   
  if   (NULL   ==   strchr(pattern,   *p))   
  break;   
  p++;   
  }   
  memmove(str,   p,   strlen(p)   +   1);   
    
  return   str;   
  }   

 char*   trimright(char*   str,   const   char*   pattern   /*   =   "   \t"   */)   
  {   
  char* p   =   str   +   strlen(str)   -   1;   
  while   (p   >=   str)   
  {   
  if   (NULL   ==   strchr(pattern,   *p))   
  break;   
  p--;   
  }   
  p++; *p   =   '\0';   
    
  return   str;   
  }   

char* trim(char* str)
{
	str = trimleft(str," \t");
	str = trimright(str," \t");
	return str;
}


/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
int InitializeComponent()
{
	int ret = ReadResources();
	if (ret==GUI_ERR_FILE_NOT_OPEN)
		return ret;
 	else	
	{
		if (ret) WritestrLog(MODULE_GUI, "Read resource file mystrings.*.txt error.");
//		return ret;
	}
//localization part

	GdkColor gray,blue;	
	gdk_color_parse ("gray", &gray);
	gdk_color_parse ("blue", &blue);
	gtk_window_set_title (GTK_WINDOW (AgentWindow), g_resManager.T_strTCAgentTitle);

	setbuttontext(AgentWindow,"btnOK",g_resManager.T_strBtnOK);
	setbuttontext(AgentWindow,"btnCancel",g_resManager.T_strBtnCancel);
	setbuttontext(AgentWindow,"btnApply",g_resManager.T_strBtnApply);

	setbuttontext(AgentWindow, "checkbutton1", g_resManager.T_strcheckBoxUseProxy); //add by xu jun 
	
	setcolor(AgentWindow,"label4",&blue);
	setlabeltext(AgentWindow,"label4",g_resManager.T_strgroupServer);
	setlabeltext(AgentWindow,"label5",g_resManager.T_strlabServer);

	setcolor(AgentWindow,"label6",&blue);
	setlabeltext(AgentWindow,"label6",g_resManager.T_strgroupProxy);
	setlabeltext(AgentWindow,"label7",g_resManager.T_strlabProxy);
	setlabeltext(AgentWindow,"label8",g_resManager.T_strlabProxyName);
	setlabeltext(AgentWindow,"label9",g_resManager.T_strlabProxyPwd);
	
	gtk_window_set_title (GTK_WINDOW (RebootWindow), g_resManager.R_strlabTitle  );
	setlabeltext(RebootWindow,"label63",g_resManager.R_strgroupPrompt  );

	setlabeltext(RebootWindow,"label64",g_resManager.R_labInfo   );
	setlabeltext(RebootWindow,"label65",g_resManager.R_labRemain   );
	setlabeltext(RebootWindow,"label66",g_resManager.R_labSecond   );

	setbuttontext(RebootWindow,"btnReboot",g_resManager.R_btnRebootNow );
		
	gtk_window_set_title (GTK_WINDOW (AboutWindow), g_resManager.A_strTitle  );

	setlabeltext(AboutWindow,"label70",g_resManager.A_strLicense   );
}

/// <summary>
/// Get Server Info form TCAgentConfig.ini to init entry
/// </summary>
int LoadServerInfo()
{
	ServerInfo serverinfo ;
	int ret = ServerInfo_Construct(&serverinfo);
	//if (ret) return ret;

	setentrytext(AgentWindow, "entryServer",serverinfo.ServerAddress);
	setentrytext(AgentWindow, "entryProxy",serverinfo.ProxyAddress);
	setentrytext(AgentWindow, "entryName",serverinfo.ProxyUser);
	setentrytext(AgentWindow, "entryPwd",serverinfo.ProxyPwd);

	int enabled=0;
	ServerInfo_UseProxy(&enabled,"GET");
	EnableProxyServer(enabled);
	
	return 0;
}

int UpdateUIbyStatus()
{
	int ret = GUI_UpdateUIByStatus(TCEngine_GetCurrentSate(&tcEngine));
	return ret;
}


/// <summary>
/// StoreUIData
/// </summary>
int StoreUIData()
{
	int ret = 0;
		
	ServerInfo serverinfo;
	
	ret = ServerInfo_Construct(&serverinfo);
	if (ret) return ret;
	
	ServerInfo_ServerAddress(getentrytext(AgentWindow,"entryServer"),"SET");
	ServerInfo_ProxyAddress(getentrytext(AgentWindow,"entryProxy"),"SET");
	ServerInfo_ProxyUser(getentrytext(AgentWindow,"entryName"),"SET");
	ServerInfo_ProxyPwd(getentrytext(AgentWindow,"entryPwd"),"SET");
	bool enabled = gtk_toggle_button_get_active((GtkToggleButton *)lookup_widget(AgentWindow,"checkbutton1"));
	
	ServerInfo_UseProxy(&enabled,"SET");	
	ret = LoadServerInfo();
	if (ret) return ret;

	setbuttondisabled(AgentWindow,"btnApply");
	
}

/// <summary>
/// Ok button click,save setting and minisize form
/// </summary>
int OkButton_Click()
{
	int ret=0;
	if(CheckInputDataRight())
	{
		ret = StoreUIData();
		if (ret != 0) WriteLog(ret);
	
		/*if (getbuttonstatus(AgentWindow, "btnApply"))//enabled
		{
			ret = UpdateUIbyStatus();
			if (ret != 0) WriteLog(ret);
		}*///modify:zhangxian Date:20081229
		setbuttondisabled(AgentWindow, "btnApply");
		
		//if (m_status != STATUS_DOWNLOADING)
		//{
			/*ret = UpdateUIbyStatus();
			if (ret != 0) WriteLog(ret);*///modify:zhangxian Date:20081229
		//}
		return 0;
	
	}
}

/// <summary>
/// Apply Button Click
/// </summary>

int ApplyButton_Click()
{
	int ret=0;
	if(CheckInputDataRight())
	{
		
		ret = StoreUIData();
		if (ret != 0) WriteLog(ret);
	
		setbuttondisabled(AgentWindow, "btnApply");

		//if (m_status != STATUS_DOWNLOADING)
		//{
		/*      ret = UpdateUIbyStatus();
		      if (ret != 0) WriteLog(ret);*///modify:zhangxian Date:20081229
		//}	
	}

	return 0;
}

/// <summary>
/// Cancel Button Click
/// </summary>


int CancelButton_Click()
{
	int ret=0;
	ret = LoadServerInfo();
	if (ret != 0) WriteLog(ret);
	setbuttondisabled(AgentWindow, "btnApply");
}



/// <summary>
/// judge the ProxyName range right
/// </summary>
/// <returns>TRUE right; FALSE error</returns>
bool IsProxyNameRight()
{
	bool bReturn = FALSE;
	char * name = getentrytext(AgentWindow,"entryName"); 
	char * proxy = getentrytext(AgentWindow,"entryProxy");
	
	if(strlen(name) != 0)
	{
		if(strlen(proxy) != 0)
		bReturn = TRUE;
		else
		bReturn = FALSE;
	}
	else
	{
		bReturn = TRUE;
	}
	if(!bReturn)
	{
		MSGBOX(ERROR_MSGBOX, "", g_resManager.M_strNeedProxyAddress);
		setfocus(AgentWindow,"entryProxy");
	}
	return bReturn;
}

/// <summary>
/// judge the ProxyPwd range right
/// </summary>
/// <returns>TRUE right; FALSE error</returns>
bool IsProxyPwdRight()
{
	bool bReturn = FALSE;
	char * name = getentrytext(AgentWindow,"entryName");
	char * pwd = getentrytext(AgentWindow,"entryPwd"); 
	char * proxy = getentrytext(AgentWindow,"entryProxy");
	if(strlen(pwd)  != 0)
	{
		if(strlen(proxy)  != 0)
		{
			if(strlen(name)  != 0)
		
			bReturn = TRUE;
	
			else
			{
				bReturn = FALSE;
				MSGBOX(ERROR_MSGBOX, "", g_resManager.M_strNeedProxyName );
				
				setfocus(AgentWindow,"entryName");
			}
		}
		else
		{
			if(strlen(name) != 0)
			{
				bReturn = TRUE;
				MSGBOX(ERROR_MSGBOX, "", g_resManager.M_strNeedProxyName );
				
				setfocus(AgentWindow,"entryName");
	
			}
			else
			{
				bReturn = FALSE;
				MSGBOX(ERROR_MSGBOX, "", g_resManager.M_strNeedAddressAndName );
				setfocus(AgentWindow,"entryProxy");
	
	
			}
		}
	}
	else
	{
		bReturn = TRUE;
	}
	return bReturn;
}

/// <summary>
/// Check the input data right 
/// </summary>
/// <returns>TRUE: date right	FALSE: date error</returns>
bool CheckInputDataRight()
{
	
	/* Check proxy name*/
	if(!IsProxyNameRight())
	{
		return FALSE;
	}
	/* Check proxy password*/
	if(!IsProxyPwdRight())
	{
		return FALSE;
	}
	return TRUE;
}

/// <summary>
/// Download cert
/// </summary>
/// <param name="nCertKind"></param> 
 int DownloadControl(int nCertKind)
{
	pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
	int ret = 0;

	ret = pthread_mutex_trylock(&mutex);
	if (ret )//lock fail
	{
	//	MSGBOX(INFORMATION_MSGBOX, g_resManager.M_strMsgTitleInfomation, g_resManager.M_strAutoDownloading);
		return 1;
	}
	int provisioned=0;
	/* Download cert*/
	
	OtherInfo_Provisioned(&provisioned, "GET");
	
	if(provisioned){
	if((ret = TCEngine_DownloadCert(&tcEngine,nCertKind))== 0)
	{
		WritestrLog(MODULE_GUI,"Auto HTTPS Download Success!");
	}
	else
	{
		//WriteLog(ret);
		//WritestrLog(MODULE_GUI,"Auto HTTPS Download Fail!");
		if (ret == ConnMgmt_ExceptionStatus_TrustFailure || ret == ConnMgmt_SOAP_SSL_ERROR)
		{
				ret = TCEngine_HTTPDownload(&tcEngine, DOWNLOADKIND_CA);
				if (ret){WriteLog(ret);WritestrLog(MODULE_GUI,"Auto HTTP Download (DOWNLOADKIND_CA) Fail!");}
		}
	}
	}
	else
	{
        ret = TCEngine_HTTPDownload(&tcEngine, DOWNLOADKIND_PROVISION);
          if (ret)
			{
				WriteLog(ret);
				WritestrLog(MODULE_GUI,"Auto HTTP Download (DOWNLOADKIND_PROVISION) Fail!");
				//pthread_mutex_unlock(&mutex);
				return ret;
			}

               provisioned = 1;
               OtherInfo_Provisioned(&provisioned, "SET");

	}
	pthread_mutex_unlock(&mutex);
	return ret;
}

int HeartbeatDownload()
{
	/*if (!otherInfo.Actived)
	{
		WritestrLog("the server doesn't approve the account yet.");
		//	gtk_timeout_remove(m_timer_autodownload);
		pthread_exit(0);//in SAS, it should exit from OS
	}*/
	
	
	pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
	int ret = 0;

	ret = pthread_mutex_trylock(&mutex);
	if (ret )//lock fail
	{
		//MSGBOX(INFORMATION_MSGBOX, g_resManager.M_strMsgTitleInfomation, g_resManager.M_strAutoDownloading);
		return 1;
	}

	m_status = TCEngine_GetCurrentSate(&tcEngine);
	

	if (m_status & STATUS_WARNING)
	{	// Warning
		//if(!m_bWarningDownload)	// warning haven't download
		//{
		//	m_status = STATUS_DOWNLOADING;
		//	m_bWarningDownload = TRUE;
		
			WritestrLog(MODULE_GUI,"Auto HTTPS Download Start!");
			if (!m_bDownloaded)  
			if((ret = DownloadControl(DOWNLOADKIND_PULL))== 0)
			{
				
				m_bDownloaded = TRUE;
				WritestrLog(MODULE_GUI,"Auto HTTPS  PULL Download Success!");
			
			}
		
		//}
	}
	else
	{
	//	if (!m_bDownloaded)  
		if((ret = DownloadControl(DOWNLOADKIND_PUSH))==0)
			{
				//m_bDownloaded = TRUE;
				WritestrLog(MODULE_GUI,"Auto HTTPS PUSH Download Success!");
				//If download success, stop Heartbeat
				gtk_timeout_remove(m_timer_autodownload);
			}
		
	}
//	if (!ret)
		ret = UpdateUIbyStatus(); // if download failed not update UI
	if (ret)WriteLog(ret);
	ret = pthread_mutex_unlock(&mutex);
	pthread_exit(0);
}


/// <summary>
/// heart beat Timer, autodownload every ten minutes
/// </summary>

int HeartbeatDownload_Tick()
{
	int ret = 0;

	pthread_t MyThread;
	ret = pthread_create(&MyThread, NULL, HeartbeatDownload, NULL);
	if (ret) 
	{
		WritestrLog(MODULE_GUI, "fork error.");
		return FALSE;
	}
	ret = pthread_join(MyThread, (void **)NULL);
	if (ret) 
	{

		WritestrLog(MODULE_GUI, "thread join error.");
		return FALSE;
	}
	return TRUE;
}	



int DownloadPushCert()
{
	
	pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
	int ret = 0;

	ret = pthread_mutex_trylock(&mutex);
	if (ret )//lock fail
	{
		//MSGBOX(INFORMATION_MSGBOX, g_resManager.M_strMsgTitleInfomation, g_resManager.M_strAutoDownloading);
		return 1;
	}

	
	if((ret = DownloadControl(DOWNLOADKIND_PUSH))==0)
	{
		
		WritestrLog(MODULE_GUI,"Auto HTTPS Download Success!");
		//If download success, stop Heartbeat
		gtk_timeout_remove(m_timer_pushdownload);
	}
	else
	{
		m_DownloadPushTimes++;
		if (m_DownloadPushTimes>10)//exit downloading push cert after fail ten times
			gtk_timeout_remove(m_timer_pushdownload);
	}
	if (!ret)
		ret = UpdateUIbyStatus(); // if download failed not update UI
	if (ret)WriteLog(ret);
	ret = pthread_mutex_unlock(&mutex);
	pthread_exit(0);
}

/// <summary>
/// push cert Timer, autodownload after system reboot
/// </summary>

int PushDownload_Tick()
{
	int ret = 0;

	pthread_t MyThread;
	ret = pthread_create(&MyThread, NULL, DownloadPushCert, NULL);
	if (ret) 
	{
		WritestrLog(MODULE_GUI, "fork error.");
		return FALSE;
	}
	ret = pthread_join(MyThread, (void **)NULL);
	if (ret) 
	{

		WritestrLog(MODULE_GUI, "thread join error.");
		return FALSE;
	}
	return TRUE;
}	




int DownloadHttp()
{
	pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
	int ret = 0;

	ret = pthread_mutex_trylock(&mutex);
	if (ret )//lock fail
	{
		WritestrLog(MODULE_GUI,"DownloadHttp: lock fail!");
	//	MSGBOX(INFORMATION_MSGBOX, g_resManager.M_strMsgTitleInfomation, g_resManager.M_strAutoDownloading);
		return 1;
	}

	ret = TCEngine_HTTPDownload(&tcEngine,DOWNLOADKIND_PROVISION );
	if (ret){WriteLog(ret);WritestrLog(MODULE_GUI,"HTTP Download Fail!");}

	ret = pthread_mutex_unlock(&mutex);
	pthread_exit(0);
}
//start the auto provision process,
int AutoProvision()
{
	int ret = 0;

	pthread_t MyThread;
	ret = pthread_create(&MyThread, NULL, DownloadHttp, NULL);
	if (ret) 
	{
		WritestrLog(MODULE_GUI, "fork error.");
		return FALSE;
	}
	ret = pthread_join(MyThread, (void **)NULL);
	if (ret) 
	{

		WritestrLog(MODULE_GUI, "thread join error.");
		return FALSE;
	}
	return TRUE;
}	


int FormTCAgent()
{
	InitializeComponent();
	
	m_bDownloaded= FALSE;	// alreadly download success once
	//m_bWarningDownload  = FALSE;	// Warning already download once
	m_status = STATUS_NORMAL;

	OtherInfo otherInfo;
	OtherInfo_Construct(&otherInfo);
	if ( otherInfo.Heartbeat_Interval > 0)
		m_autointerval = atoi( otherInfo.Heartbeat_Interval) * 60 * 1000;//from minutes to mseconds
	m_timer_autodownload = gtk_timeout_add(m_autointerval,HeartbeatDownload_Tick,NULL);
	m_timer_pushdownload = gtk_timeout_add(PUSHCERT_DOWNLOAD_INTERVAL,PushDownload_Tick,NULL);
	int ret = TCEngine_Construct(&tcEngine);
	if (ret){
		WritestrLog(MODULE_GUI, "tcengine initialization fail" );
		return ;
	}	
	ret = OtherInfo_LastDate("","SET");
	if (ret) WriteLog(ret);
	ret = OtherInfo_LastTimes("","SET");
	if (ret) WriteLog(ret);
}



/// <summary>
/// Form load, auto download cert and Update UI by Status().
/// </summary>

int TCAgentForm_Load()
{
	int ret=0;	
	WritestrLog(MODULE_GUI, "tcagent form load");
	//ret = CopyCACertInfo();//no data import module in CMPC 1.5
	//if (ret) WriteLog(ret);
	
/*
	//exit the program if the Enabled status is false
	OtherInfo otherInfo;
	OtherInfo_Construct(&otherInfo);
		WritestrLog(MODULE_GUI, "tcagent is disabled, now is exiting");
		return GUI_ERR_AGENT_DISABLE;
	}

	
	if (otherInfo.Actived && ! otherInfo.Provisioned ){//the account is activated as normal account, while not provision yet
		WritestrLog(MODULE_GUI, "tcagent is not provisioined, now start the Download autoprovision packet");
		AutoProvision();
	}*/

	setbuttondisabled(AgentWindow,"btnApply");
	//Check the checkbox to set the entry sensitive or insensitive
	int enabled=0;
	ServerInfo_UseProxy(&enabled,"GET");
	EnableProxyServer(enabled);
	
	/*ret = UpdateUIbyStatus();
	if (ret != 0) WriteLog(ret);*///modify:zhangxian Date:20081229
	
	ret = LoadServerInfo();
	if (ret != 0) WriteLog(ret);

	

	return 0;
}


int RebootDevice_Clicked()
{
	system("sudo reboot &");
	system("dcop ksmserver default logout 0 1 0 &");
	return 0;
}
/// <summary>
/// Reboot Device
/// </summary>
int RebootDevice()
{
	gtk_timeout_remove(m_timer_autodownload);
	gtk_timeout_remove(m_timer_pushdownload);
	if(!m_bRebootForm)
	{
	// form reboot is always on in 60 second,or before reboot buttonclick
		m_bRebootForm = TRUE;
	
		gtk_window_set_position(GTK_WINDOW (RebootWindow),	GTK_WIN_POS_CENTER_ON_PARENT);
		gtk_window_set_modal(GTK_WINDOW (RebootWindow), TRUE);
		    
		gtk_widget_show(RebootWindow);
	}

}
/// <summary>
/// entry text changed evens,
/// the Apply button can used if entrys changed.
/// </summary>


int entryPwd_TextChanged()
{
	setbuttonenabled(AgentWindow, "btnApply");
}


gint update_reboot_time(gpointer data)
{
	int remainseconds = atoi(getlabeltext(RebootWindow, "labelRemainSeconds"));
	char tmp[TEMP_MAX_LEN];
		
	if (remainseconds>60 || remainseconds <=0)
	{
		RebootDevice_Clicked();
		gtk_widget_hide(RebootWindow);
		return FALSE;
	}
	else
	{
		sprintf(tmp, "%d", remainseconds -  1);
		setlabeltext(RebootWindow,"labelRemainSeconds",tmp);
		return TRUE;	
	}
}


/// <summary>
/// System restart,when download special cert or shared secret success
/// do nothing when command cert download success
/// </summary>
/// <param name="e">DownloadCertFinishEventArgs</param>
int tcEngine_DownloadCertFinish(DownloadCertFinishEventArgs* dcfEventArgs)
{
	// download success
	//gtk_progress_bar_set_fraction(lookup_widget(GTK_WIDGET(ProgressWindow),"progressbar1"),0.9);//set the progress bar 100%
	if(dcfEventArgs->DownloadStatus==0)
	{
// reboot system if cert is shared secret or special cert
		if(dcfEventArgs->CertKind == SharedSecret ||
   			dcfEventArgs->CertKind == SpecialCert ||
			dcfEventArgs->CertKind == AutoProvisionPackage ||
			dcfEventArgs->CertKind == ServerPublicKey ||
			dcfEventArgs->CertKind == IntelPublicKey
			)

		RebootDevice();
		else if (dcfEventArgs->CertKind == CAPackage)
		{
			WritestrLog(MODULE_GUI, "Root CA verify error, the root CA Package was downloaded again!");
		//	MSGBOX(INFORMATION_MSGBOX, g_resManager.M_strMsgTitleInfomation, g_resManager.G_strDownloadCASuceed );
		}
		else
		{
			//m_bDownloaded = TRUE;
 		//	MSGBOX(INFORMATION_MSGBOX, g_resManager.M_strMsgTitleInfomation, g_resManager.M_strDownloadSuccess );
		}
			
		UpdateUIbyStatus();
		destroywindow();

	}
	//gtk_widget_hide(ProgressWindow);
} // end of int tcEngine_DownloadCertFinish

int destroywindow()
{
    DateTime dateExpiration;
    int nBootCount;
	int ret=0;


    /* Get expireation info from tcEngine*/
    ret = TCEngine_GetExpirationInfo(&tcEngine, &dateExpiration, &nBootCount);
	if (ret) {WriteLog(ret);ErrMsgBox(ret);return ret;}
	char tmp[TEMP_MAX_LEN];

	sprintf(tmp,"%4d-%2d-%2d",dateExpiration.Year,dateExpiration.Month,dateExpiration.Day);
	ret = OtherInfo_LastDate(tmp,"SET");

	if (ret) WriteLog(ret);
	sprintf(tmp,"%d",nBootCount);
	ret = OtherInfo_LastTimes(tmp,"SET");
	if (ret) WriteLog(ret);

}

bool EnableProxyServer(bool enabled)
{
gtk_toggle_button_set_active((GtkToggleButton *)lookup_widget(AgentWindow,"checkbutton1"),enabled);
	if (enabled)
	{
	    setbuttonenabled(AgentWindow,"entryProxy");
		setbuttonenabled(AgentWindow,"entryName");
		setbuttonenabled(AgentWindow,"entryPwd");
	}
	else
	{	
		setbuttondisabled(AgentWindow,"entryProxy");
		setbuttondisabled(AgentWindow,"entryName");
		setbuttondisabled(AgentWindow,"entryPwd");
	}
	return 0;
}


int GUI_ShowAgentWindow()
{
	gtk_window_set_position(GTK_WINDOW (AgentWindow),GTK_WIN_POS_CENTER);
	gtk_window_set_keep_above (GTK_WINDOW (AgentWindow), TRUE);  
	gtk_window_set_modal (GTK_WINDOW (AgentWindow), FALSE);
	gtk_widget_show(AgentWindow);
	
}
