/*
	$Id: SettingsForm.cs 60 2010-01-30 09:23:29Z catwalk $
*/
using System;
using System.Linq;
using System.ComponentModel;
using System.Configuration;
using System.Collections.Generic;
using System.Windows;
using System.Windows.Data;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Interop;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Windows.Threading;
using System.Reflection;
using System.Net;
using Hiyoko.Net.Twitter;
using Hiyoko.Net.OAuth;
using Hiyoko.Themes;
using Microsoft.WindowsAPICodePack.Shell;

namespace Hiyoko.Forms{
	using WinForms = System.Windows.Forms;
	using Gdi = System.Drawing;
	using IO = System.IO;
	
	public partial class SettingsForm : Window{
		private RequestToken requestToken = null;
		
		public SettingsForm(){
			this.InitializeComponent();
			
			this.TempSettings = new ApplicationSettings();
			Program.Settings.CopyTo(this.TempSettings);
			this.DataContext = this.TempSettings;
			this.twitpicPasswordEdit.Password = this.TempSettings.TwitpicPassword;
			
			try{
				this.themesBox.DataContext = new KeyValuePair<string, ITheme>[]{
					new KeyValuePair<string, ITheme>("(none)", ThemeBase.Empty)}.Concat(
						Program.ThemeManager.Themes.Select(t => new KeyValuePair<string, ITheme>(t.Name, t)));
			}catch(Exception){
			}
		}
		
		#region イベント処理
		
		private void OpenStartupScriptPath(object sender, EventArgs e){
			WinForms.OpenFileDialog dlg = new WinForms.OpenFileDialog();
			dlg.Filter = "Pyファイル|*.py";
			dlg.DefaultExt = "py";
			dlg.CheckPathExists = false;
			dlg.CheckFileExists = false;
			if(dlg.ShowDialog() == WinForms.DialogResult.OK){
				this.startupScriptPathEdit.Text = dlg.FileName;
			}
		}
		
		private void OpenAuthPageClick(object sender, EventArgs e){
			try{
				this.requestToken = TwitterAPI.ObtainUnauthorizedRequestToken();
				System.Diagnostics.Process.Start(TwitterAPI.BuildUserAuthorizationURL(this.requestToken));
				this.authRequestTokenButton.IsEnabled = true;
			}catch(WebException ex){
				MessageBox.Show(ex.Message, "通信失敗", MessageBoxButton.OK, MessageBoxImage.Error);
			}
		}
		
		private void AuthRequestTokenClick(object sender, EventArgs e){
			try{
				AccessToken accessToken = TwitterAPI.GetAccessToken(this.requestToken, this.accessTokenVerifierEdit.Text);
				this.TempSettings.AccessToken = accessToken;
				MessageBox.Show("OAuth認証が成功しました。", "認証成功", MessageBoxButton.OK, MessageBoxImage.Asterisk);
			}catch(WebException ex){
				MessageBox.Show(ex.Message, "認証失敗", MessageBoxButton.OK, MessageBoxImage.Error);
			}
		}
		
		private void OpenAddtionalDictionary(object sender, EventArgs e){
			WinForms.OpenFileDialog dlg = new WinForms.OpenFileDialog();
			dlg.CheckPathExists = false;
			dlg.CheckFileExists = false;
			if(dlg.ShowDialog() == WinForms.DialogResult.OK){
				this.autoCompleteAddtionalDictionaryEdit.Text = dlg.FileName;
			}
		}
		
		#endregion
		
		#region コマンド
		
		private void Close_CanExecute(object target, CanExecuteRoutedEventArgs e){
			e.CanExecute = true;
		}
		
		private void Close_Execute(object target, ExecutedRoutedEventArgs e){
			this.Close();
		}
		
		private void Save_CanExecute(object target, CanExecuteRoutedEventArgs e){
			e.CanExecute = true;
		}
		
		private void Save_Execute(object target, ExecutedRoutedEventArgs e){
			this.TempSettings.TwitpicPassword = this.twitpicPasswordEdit.Password;
			this.TempSettings.CopyTo(Program.Settings);
			Program.Settings.Save();
			this.DialogResult = true;
			this.Close();
		}
		
		private void Apply_CanExecute(object target, CanExecuteRoutedEventArgs e){
			e.CanExecute = true;
		}
		
		private void Apply_Execute(object target, ExecutedRoutedEventArgs e){
			this.TempSettings.TwitpicPassword = this.twitpicPasswordEdit.Password;
			this.TempSettings.CopyTo(Program.Settings);
		}
		
		private void Reset_CanExecute(object target, CanExecuteRoutedEventArgs e){
			e.CanExecute = true;
		}
		
		private void Reset_Execute(object target, ExecutedRoutedEventArgs e){
			if(MessageBox.Show("設定を初期値に戻してよろしいですか？", "設定の初期化", MessageBoxButton.YesNo) == MessageBoxResult.Yes){
				this.TempSettings.Reset();
			}
		}
		
		private void ShowThemeSettings_CanExecute(object target, CanExecuteRoutedEventArgs e){
			if((this.themesBox != null) && (this.themesBox.SelectedIndex != -1) && (this.themesBox.SelectedItem != null)){
				var theme = ((KeyValuePair<string, ITheme>)this.themesBox.SelectedItem).Value;
				e.CanExecute = (theme != null) && theme.CanShowSettings;
			}else{
				e.CanExecute = false;
			}
		}
		
		private void ShowThemeSettings_Execute(object target, ExecutedRoutedEventArgs e){
			var theme = ((KeyValuePair<string, ITheme>)this.themesBox.SelectedItem).Value;
			if(theme.ShowSettings(this).Value){
				Program.Settings.ThemeGuid = this.TempSettings.ThemeGuid;
			}
		}
		
		#endregion
		
		#region プロパティ
		
		public static readonly DependencyProperty RequestTokenProperty = DependencyProperty.Register("RequestToken", typeof(RequestToken), typeof(SettingsForm));
		private RequestToken RequestToken{
			get{
				return (RequestToken)this.GetValue(RequestTokenProperty);
			}
			set{
				this.SetValue(RequestTokenProperty, value);
			}
		}
		
		public static readonly DependencyProperty TempSettingsProperty = DependencyProperty.Register("TempSettings", typeof(ApplicationSettings), typeof(SettingsForm));
		private ApplicationSettings TempSettings{
			get{
				return (ApplicationSettings)this.GetValue(TempSettingsProperty);
			}
			set{
				this.SetValue(TempSettingsProperty, value);
			}
		}
		
		public TabItem AuthTabI{
			get{
				return this.authTab;
			}
		}
		
		public TabItem ApplicationTab{
			get{
				return this.appTab;
			}
		}
		
		public TabItem ThemeTab{
			get{
				return this.themeTab;
			}
		}
		
		public TabItem NetworkTab{
			get{
				return this.networkTab;
			}
		}
		
		public TabItem UrlShorterTab{
			get{
				return urlShorterTab;
			}
		}
		
		public TabItem UploadTab{
			get{
				return this.uploadTab;
			}
		}
		
		#endregion
	}
	
	internal class IsEmptyGuidConverter : IValueConverter{
		public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture){
			var guid = (Guid)value;
			return guid == Guid.Empty;
		}
		
		public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture){
			throw new NotImplementedException();
		}
	}
}