Temp fixes
[pithos-ms-client] / trunk / Pithos.Client.WPF / Preferences / PreferencesViewModel.cs
index 8ece12c..2857dc8 100644 (file)
  */
 #endregion
 
-// </copyright>
-// -----------------------------------------------------------------------
 
 using System.Collections.Concurrent;
+using System.Collections.Generic;
 using System.ComponentModel.Composition;
+using System.Diagnostics;
 using System.IO;
-using System.Net;
+using System.Reflection;
 using System.Threading.Tasks;
 using System.Windows;
 using System.Windows.Forms;
 using Caliburn.Micro;
 using Pithos.Client.WPF.Configuration;
+using Pithos.Client.WPF.Properties;
 using Pithos.Client.WPF.SelectiveSynch;
 using Pithos.Core;
 using Pithos.Interfaces;
@@ -62,13 +63,20 @@ using Screen = Caliburn.Micro.Screen;
 namespace Pithos.Client.WPF.Preferences
 {
     /// <summary>
-    /// TODO: Update summary.
+    /// The preferences screen displays user and account settings and updates the PithosMonitor
+    /// classes when account settings change.
     /// </summary>
+    /// <remarks>
+    /// The class is a single ViewModel for all Preferences tabs. It can be broken in separate
+    /// ViewModels, one for each tab.
+    /// </remarks>
     [Export]
     public class PreferencesViewModel : Screen
     {
-        private IEventAggregator _events;
+        private readonly IEventAggregator _events;
 
+        //Logging in the Pithos client is provided by log4net
+        private static readonly log4net.ILog Log = log4net.LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
 
         private PithosSettings _settings;
         public PithosSettings Settings
@@ -81,8 +89,8 @@ namespace Pithos.Client.WPF.Preferences
             }
         }
 
-        private ObservableConcurrentCollection<AccountSettings> _accounts;
-        public ObservableConcurrentCollection<AccountSettings> Accounts
+        private ObservableConcurrentCollection<AccountViewModel> _accounts;
+        public ObservableConcurrentCollection<AccountViewModel> Accounts
         {
             get { return _accounts; }
             set 
@@ -99,20 +107,27 @@ namespace Pithos.Client.WPF.Preferences
 
         public PreferencesViewModel(IWindowManager windowManager, IEventAggregator events, ShellViewModel shell, PithosSettings settings, string currentTab)
         {
+            // ReSharper disable DoNotCallOverridableMethodsInConstructor
+            //Caliburn.Micro uses DisplayName for the view's title
+            DisplayName = "Pithos+ Preferences";
+            // ReSharper restore DoNotCallOverridableMethodsInConstructor
+
             _windowManager = windowManager;
             _events = events;
 
-            DisplayName = "Pithos Preferences";
             Shell = shell;
             
             Settings=settings;
-            Accounts = new ObservableConcurrentCollection<AccountSettings>();
+            Accounts = new ObservableConcurrentCollection<AccountViewModel>();
             if (settings.Accounts == null)
             {
                 settings.Accounts=new AccountsCollection();
                 settings.Save();
             }
-            Accounts.AddFromEnumerable(settings.Accounts);
+            var accountVMs = from account in settings.Accounts
+                             select new AccountViewModel(account);
+
+            Accounts.AddFromEnumerable(accountVMs);
             
             var startupPath = Environment.GetFolderPath(Environment.SpecialFolder.Startup);
             _shortcutPath = Path.Combine(startupPath, "Pithos.lnk");
@@ -187,7 +202,7 @@ namespace Pithos.Client.WPF.Preferences
             set
             {
                 if (value<0)
-                    throw new ArgumentOutOfRangeException("value","The Startup Delay must be greater or equal to 0");
+                    throw new ArgumentOutOfRangeException("value",Resources.PreferencesViewModel_StartupDelay_Greater_or_equal_to_0);
                 Settings.StartupDelay = TimeSpan.FromMinutes(value);
                 NotifyOfPropertyChange(()=>StartupDelay);
             }
@@ -205,19 +220,63 @@ namespace Pithos.Client.WPF.Preferences
             var monitor = Shell.Monitors[CurrentAccount.AccountName];
             
 
-            var model = new SelectiveSynchViewModel(monitor,_events,CurrentAccount);
+            var model = new SelectiveSynchViewModel(monitor,_events,CurrentAccount.Account);
             if (_windowManager.ShowDialog(model) == true)
             {
                 
             }
         }
 
-        public async Task RefreshApiKey()
-        {            
-            await Shell.TryAuthorize(CurrentAccount.AccountName, 3);
-            NotifyOfPropertyChange(()=>CurrentAccount);
+        public void RefreshApiKey()
+        {
+            //_events.Publish(new Notification { Title = "Authorization failed", Message = "Your API Key has probably expired. You will be directed to a page where you can renew it", Level = TraceLevel.Error });
+            if (CurrentAccount == null)
+                return;
+            try
+            {
+
+                var name = CurrentAccount.AccountName;
+
+                var loginUri = new Uri(new Uri(CurrentAccount.ServerUrl), "login");
+                var credentials = PithosAccount.RetrieveCredentials(loginUri.ToString(),name);
+                if (credentials==null)
+                    return;
+                //The server will return credentials for a different account, not just the current account
+                //We need to find the correct account first
+                var account = Accounts.First(act => act.AccountName == credentials.UserName && act.ServerUrl == ?? );
+                account.ApiKey = credentials.Password;                
+                account.IsExpired = false;
+                Settings.Save();
+                TaskEx.Delay(10000).ContinueWith(_ =>Shell.MonitorAccount(account.Account));
+                NotifyOfPropertyChange(() => Accounts);
+            }
+            catch (AggregateException exc)
+            {
+                string message = String.Format("API Key retrieval failed");
+                Log.Error(message, exc.InnerException);
+                _events.Publish(new Notification { Title = "Authorization failed", Message = message, Level = TraceLevel.Error });
+            }
+            catch (Exception exc)
+            {
+                string message = String.Format("API Key retrieval failed");
+                Log.Error(message, exc);
+                _events.Publish(new Notification { Title = "Authorization failed", Message = message, Level = TraceLevel.Error });
+            }
+
         }
+
     
+        public void OpenLogPath()
+        {
+            Shell.OpenLogPath();
+        }
+
+        public void OpenLogConsole()
+        {
+            var logView=IoC.Get<LogConsole.LogConsoleViewModel>();            
+            _windowManager.ShowWindow(logView);
+        }
+
         public void SaveChanges()
         {
             DoSave();
@@ -237,12 +296,39 @@ namespace Pithos.Client.WPF.Preferences
 
         private void DoSave()
         {
-            Settings.Save();
             //SetStartupMode();            
 
-            foreach (var account in Settings.Accounts)
-            {                                
-                Shell.MonitorAccount(account);
+            //Ensure we save the settings changes first
+            foreach (var account in _accountsToRemove)
+            {
+                Settings.Accounts.Remove(account);
+            }
+
+            foreach (var account in _accountsToAdd)
+            {
+                Settings.Accounts.Add(account);    
+            }
+
+            Settings.Save();
+
+
+            try
+            {
+                foreach (var account in _accountsToRemove)
+                {
+                    Shell.RemoveMonitor(account.AccountName);
+                    Shell.RemoveAccountFromDatabase(account);
+                }
+
+                foreach (var account in Settings.Accounts)
+                {
+                    Shell.MonitorAccount(account);
+                }
+            }                
+            finally
+            {
+                _accountsToRemove.Clear();
+                _accountsToAdd.Clear();
             }
 
             NotifyOfPropertyChange(()=>Settings);
@@ -273,21 +359,27 @@ namespace Pithos.Client.WPF.Preferences
         }
 */
 
-        
 
+        readonly List<AccountSettings> _accountsToAdd=new List<AccountSettings>();
        public void AddAccount()
        {
            var wizard = new AddAccountViewModel();
            if (_windowManager.ShowDialog(wizard) == true)
            {
                string selectedPath = wizard.AccountPath;
-               var initialRootPath = Path.Combine(selectedPath, "Okeanos");
+               var initialRootPath = wizard.ShouldCreateOkeanosFolder?
+                   Path.Combine(selectedPath, "Okeanos")
+                   :selectedPath;
                var actualRootPath= initialRootPath;
-               int attempt = 1;
-               while (Directory.Exists(actualRootPath) || File.Exists(actualRootPath))
+               if (wizard.ShouldCreateOkeanosFolder)
                {
-                   actualRootPath = String.Format("{0} {1}", initialRootPath,attempt++);
+                   int attempt = 1;
+                   while (Directory.Exists(actualRootPath) || File.Exists(actualRootPath))
+                   {
+                       actualRootPath = String.Format("{0} {1}", initialRootPath, attempt++);
+                   }
                }
+               ### Check that the account does not already exist
 
                var newAccount = new AccountSettings
                                     {
@@ -297,9 +389,10 @@ namespace Pithos.Client.WPF.Preferences
                                         RootPath = actualRootPath,
                                         IsActive=wizard.IsAccountActive
                                     };
-               Settings.Accounts.Add(newAccount);
-               (Accounts as IProducerConsumerCollection<AccountSettings>).TryAdd(newAccount);
-               CurrentAccount = newAccount;
+               _accountsToAdd.Add(newAccount);
+               var accountVm = new AccountViewModel(newAccount);
+               (Accounts as IProducerConsumerCollection<AccountViewModel>).TryAdd(accountVm);
+               CurrentAccount = accountVm;
                NotifyOfPropertyChange(() => Accounts);
                NotifyOfPropertyChange(() => Settings);   
            }
@@ -308,10 +401,14 @@ namespace Pithos.Client.WPF.Preferences
             
        }
 
-        public async void AddPithosAccount()
+/*
+        public void AddPithosAccount()
        {
-            var credentials=await PithosAccount.RetrieveCredentials(Settings.PithosLoginUrl);
+            var credentials=PithosAccount.RetrieveCredentials(null);
+            if (credentials == null)
+                return;
             var account = Settings.Accounts.FirstOrDefault(act => act.AccountName == credentials.UserName);
+            var accountVM = new AccountViewModel(account);
             if (account == null)
             {
                 account=new AccountSettings{
@@ -319,32 +416,30 @@ namespace Pithos.Client.WPF.Preferences
                     ApiKey=credentials.Password
                 };
                 Settings.Accounts.Add(account);
-                (Accounts as IProducerConsumerCollection<AccountSettings>).TryAdd(account);
+                accountVM = new AccountViewModel(account);
+                (Accounts as IProducerConsumerCollection<AccountViewModel>).TryAdd(accountVM);
             }
             else
             {
                 account.ApiKey=credentials.Password;
             }
             //SelectedAccountIndex= Settings.Accounts.IndexOf(account);
-            CurrentAccount = account;
+            CurrentAccount = accountVM;
             NotifyOfPropertyChange(() => Accounts);
             NotifyOfPropertyChange(()=>Settings);                       
        }
+*/
 
+
+        readonly List<AccountSettings> _accountsToRemove = new List<AccountSettings>();
         public void RemoveAccount()
         {
-            var accountName = CurrentAccount.AccountName;
-            Settings.Accounts.Remove(CurrentAccount);
-
             Accounts.TryRemove(CurrentAccount);
-            
-            
+            _accountsToRemove.Add(CurrentAccount.Account);
+
             CurrentAccount = null;
-            //Accounts = Settings.Accounts;
-            //Settings.Save();            
-            Shell.RemoveMonitor(accountName);
             NotifyOfPropertyChange(() => Accounts);
-            NotifyOfPropertyChange(() => Settings);                       
+
             
             //NotifyOfPropertyChange("Settings.Accounts");
         }
@@ -378,6 +473,14 @@ namespace Pithos.Client.WPF.Preferences
             }
         }
 
+        public bool DebugLoggingEnabled
+        {
+            get { return Settings.DebugLoggingEnabled; }
+            set { 
+                Settings.DebugLoggingEnabled = value;
+                NotifyOfPropertyChange(()=>DebugLoggingEnabled);
+            }
+        }
        
         #endregion
 
@@ -401,13 +504,13 @@ namespace Pithos.Client.WPF.Preferences
             }
         }*/
 
-        private AccountSettings _currentAccount;
-        private IWindowManager _windowManager;
-        private string _shortcutPath;
+        private AccountViewModel _currentAccount;
+        private readonly IWindowManager _windowManager;
+        private readonly string _shortcutPath;
 
 
         
-        public AccountSettings CurrentAccount
+        public AccountViewModel CurrentAccount
         {
             get { return _currentAccount; }
             set
@@ -475,11 +578,11 @@ namespace Pithos.Client.WPF.Preferences
                                                                             SearchOption.AllDirectories))
                         File.Copy(newFilePath, newFilePath.Replace(oldPath, newPath));
 
+                    Log.InfoFormat("Deleting account folder {0}",oldPath);
                     Directory.Delete(oldPath, true);
 
                     //We also need to change the path of the existing file states
-                    if (monitor != null)
-                        monitor.MoveFileStates(oldPath, newPath);
+                    monitor.MoveFileStates(oldPath, newPath);
                 }
             }
             //Replace the old rootpath with the new
@@ -494,7 +597,7 @@ namespace Pithos.Client.WPF.Preferences
                     monitor.Start();
             }
             else
-                Shell.MonitorAccount(CurrentAccount);
+                Shell.MonitorAccount(CurrentAccount.Account);
             //Finally, notify that the Settings, CurrentAccount have changed
             NotifyOfPropertyChange(() => CurrentAccount);
             NotifyOfPropertyChange(() => Settings);