using System;
using System.Xml;
using System.IO;
using System.Threading;
using System.Windows.Forms;
using System.Diagnostics;
using Config;
using Microsoft.ApplicationBlocks.ApplicationUpdater;
namespace HISClinic
{
	public  delegate void UpdaterCallBackHandle(object sender,UpdaterArgs args);
	public class UpdaterArgs:EventArgs {
		public UpdaterArgs(){
		}
		public UpdaterArgs(bool isrunning)
		 {
			IsRunning=isrunning;
		 }
		public bool IsRunning;
	}
	
	/// <summary>
	/// SelfUpdater 的摘要说明。
	/// </summary>
	public class SelfUpdater:IDisposable
	{
		ApplicationUpdateManager updater;
		public UpdaterCallBackHandle UpdaterStateCallBack;
		public IWin32Window MsgBoxOwner; 
		public SelfUpdater()
		{
			InitUpdater();
		}
		/// <summary>
		/// 初始化Updater
		/// </summary>
		private void InitUpdater(){
			updater=new ApplicationUpdateManager();
			updater.UpdateAvailable+=new UpdaterActionEventHandler(updater_UpdateAvailable);
			updater.FilesValidated+=new UpdaterActionEventHandler(updater_FilesValidated);		
		
		}
		/// <summary>
		/// 开始更新
		/// </summary>
		public void StartUpdate(){
			updater.StartUpdater();
			
		}
		/// <summary>
		/// 重新开始更新
		/// </summary>
		public void ReStartUpdate(){
			updater=null;
			InitUpdater();
			updater.StartUpdater();
		}
		/// <summary>
		/// 设置Polling间隔
		/// </summary>
		public int Interval{
			set{
				SavePollingIntoConfigFile(value);
			}
			get{
				return GetPollingInterval();
			}
		}
		/// <summary>
		/// 保存更新间隔，单位（秒）
		/// </summary>
		/// <param name="interval"></param>
		private void SavePollingIntoConfigFile(int interval){
			Config.ConfigFile configfile=new Config.ConfigFile(System.Reflection.Assembly.GetExecutingAssembly().Location+".config");
			configfile.UpdateInterval=interval;
			UpdaterConfiguration.Instance.Polling.Value=interval.ToString();
			UpdaterConfiguration.Instance.Polling.Type=PollingType.Seconds;

		}
		/// <summary>
		/// 日志文件，如果为空则取消日志
		/// </summary>
		public string LogFile {
			set{
				 SetLogFile(value);
			}
			get{
				return GetLogFile();
			}
		}
		/// <summary>
		/// 设置日志文件
		/// </summary>
		/// <param name="logfile"></param>
		private void SetLogFile(string logfile){
			Config.ConfigFile configfile=new Config.ConfigFile(System.Reflection.Assembly.GetExecutingAssembly().Location+".config");
			configfile.SetLogPath(logfile);
			if(logfile.Length>0)
				UpdaterConfiguration.Instance.Logging.LogPath=logfile;
			else
				UpdaterConfiguration.Instance.Logging.LogPath="";
		}
		private string GetLogFile(){
			return UpdaterConfiguration.Instance.Logging.LogPath;
		}
		/// <summary>
		/// 获取更新间隔，单位（秒）
		/// </summary>
		/// <returns></returns>
		private int GetPollingInterval(){
			Config.ConfigFile configfile=new Config.ConfigFile(System.Reflection.Assembly.GetExecutingAssembly().Location+".config");
			return configfile.UpdateInterval;


		}
		/// <summary>
		/// 停止更新
		/// </summary>
		public void StopUpdate(){
			updater.StopUpdater(UpdaterConfiguration.Instance.Applications[0].Name);
		}
		/// <summary>
		/// 实现IDisposable.Dispose接口方法，释放资源
		/// </summary>
		public void Dispose(){
			if(null!=updater){
				StopUpdate();
				updater=null;
			}
		}
		/// <summary>
		///当判定存在更新文件时相应的事件方法
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void updater_UpdateAvailable(object sender, UpdaterActionEventArgs e)
		{
			// Show a message allowing the user to determine if they would like to download the update
			// and perform the upgrade
			string message = String.Format( 
				"更新提示： 现在服务器上的最新版本是 {0} , 需要更新吗?", 
				e.ServerInformation.AvailableVersion ) ;
			DialogResult dialog ;
			if(MsgBoxOwner!=null)
				dialog = MessageBox.Show(MsgBoxOwner, message, "更新提示", MessageBoxButtons.YesNo );
			else
				dialog = MessageBox.Show( message, "更新提示", MessageBoxButtons.YesNo );
			UpdaterArgs args=new UpdaterArgs();

			// The user has indicated they don't want to upgrade
			if( DialogResult.No == dialog )
			{
				//  stop the updater for this app
				updater.StopUpdater( e.ApplicationName );
				args.IsRunning=false;
			}
			else{
				args.IsRunning=true;
			}
			if(UpdaterStateCallBack!=null)
				UpdaterStateCallBack(this,args);
		}

		/// <summary>
		/// 当更新文件下载完毕时相应的事件方法
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void updater_FilesValidated(object sender, UpdaterActionEventArgs e)
		{
			//  Ask user if they want to use the new version of the application
			DialogResult dialog = MessageBox.Show( 
				"需要打开新的应用程序吗?", 
				"打开新版本?", MessageBoxButtons.YesNo );

			if( DialogResult.Yes == dialog )
			{
				// Load this applications configuration file to read the 
				// UAB information and obtain the basedir
				XmlDocument doc = new XmlDocument();
				doc.Load( AppDomain.CurrentDomain.SetupInformation.ConfigurationFile );
				string baseDir = doc.SelectSingleNode(
					"configuration/appUpdater/UpdaterConfiguration/application/client/baseDir"
					).InnerText;
				// Figure out the path to AppStart.exe which we will chain to
				string newDir = Path.Combine( baseDir, "AppStart.exe" );
				
				// Launch AppStart.exe which will launch the new version
				ProcessStartInfo process = new ProcessStartInfo( newDir );
				process.WorkingDirectory = Path.Combine( newDir , 
					e.ServerInformation.AvailableVersion );
				Process.Start( process );

				StopUpdate();
				Environment.Exit( 0 );
			}
		}


	}

}
