Statistics
| Branch: | Revision:

root / trunk / Pithos.Client.WPF / Preferences / PreferencesViewModel.cs @ c87a1e4f

History | View | Annotate | Download (29.6 kB)

1
#region
2
/* -----------------------------------------------------------------------
3
 * <copyright file="PreferencesViewModel.cs" company="GRNet">
4
 * 
5
 * Copyright 2011-2012 GRNET S.A. All rights reserved.
6
 *
7
 * Redistribution and use in source and binary forms, with or
8
 * without modification, are permitted provided that the following
9
 * conditions are met:
10
 *
11
 *   1. Redistributions of source code must retain the above
12
 *      copyright notice, this list of conditions and the following
13
 *      disclaimer.
14
 *
15
 *   2. Redistributions in binary form must reproduce the above
16
 *      copyright notice, this list of conditions and the following
17
 *      disclaimer in the documentation and/or other materials
18
 *      provided with the distribution.
19
 *
20
 *
21
 * THIS SOFTWARE IS PROVIDED BY GRNET S.A. ``AS IS'' AND ANY EXPRESS
22
 * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
23
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
24
 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL GRNET S.A OR
25
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
26
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
27
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
28
 * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
29
 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
31
 * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
32
 * POSSIBILITY OF SUCH DAMAGE.
33
 *
34
 * The views and conclusions contained in the software and
35
 * documentation are those of the authors and should not be
36
 * interpreted as representing official policies, either expressed
37
 * or implied, of GRNET S.A.
38
 * </copyright>
39
 * -----------------------------------------------------------------------
40
 */
41
#endregion
42

    
43

    
44
using System.Collections.Concurrent;
45
using System.Collections.Generic;
46
using System.Collections.Specialized;
47
using System.ComponentModel.Composition;
48
using System.Diagnostics;
49
using System.IO;
50
using System.Net;
51
using System.Reflection;
52
using System.Threading.Tasks;
53
using System.Windows;
54
using System.Windows.Forms;
55
using Caliburn.Micro;
56
using Pithos.Client.WPF.Configuration;
57
using Pithos.Client.WPF.Properties;
58
using Pithos.Client.WPF.SelectiveSynch;
59
using Pithos.Client.WPF.Utils;
60
using Pithos.Core;
61
using Pithos.Core.Agents;
62
using Pithos.Interfaces;
63
using System;
64
using System.Linq;
65
using Pithos.Network;
66
using MessageBox = System.Windows.MessageBox;
67
using Screen = Caliburn.Micro.Screen;
68

    
69
namespace Pithos.Client.WPF.Preferences
70
{
71
    /// <summary>
72
    /// The preferences screen displays user and account settings and updates the PithosMonitor
73
    /// classes when account settings change.
74
    /// </summary>
75
    /// <remarks>
76
    /// The class is a single ViewModel for all Preferences tabs. It can be broken in separate
77
    /// ViewModels, one for each tab.
78
    /// </remarks>
79
    [Export, PartCreationPolicy(CreationPolicy.Shared)]
80
    public class PreferencesViewModel : Screen
81
    {
82
        private readonly IEventAggregator _events;
83

    
84
        //Logging in the Pithos client is provided by log4net
85
        private static readonly log4net.ILog Log =
86
            log4net.LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
87

    
88
        private PithosSettings _settings;
89

    
90
        public PithosSettings Settings
91
        {
92
            get { return _settings; }
93
            set
94
            {
95
                _settings = value;
96
                NotifyOfPropertyChange(() => Settings);
97
            }
98
        }
99

    
100
        private ObservableConcurrentCollection<AccountViewModel> _accounts;
101

    
102
        public ObservableConcurrentCollection<AccountViewModel> Accounts
103
        {
104
            get { return _accounts; }
105
            set
106
            {
107
                _accounts = value;
108
                NotifyOfPropertyChange(() => Accounts);
109
            }
110
        }
111

    
112
        public bool StartOnSystemStartup { get; set; }
113

    
114
        public ShellViewModel Shell { get; set; }
115
        //ShellExtensionController _extensionController=new ShellExtensionController();
116

    
117
        [ImportingConstructor]
118
        public PreferencesViewModel(IWindowManager windowManager, IEventAggregator events, ShellViewModel shell,
119
                                    PithosSettings settings)
120
        {
121
            this.DisplayName = "Pithos+ Preferences";
122

    
123
            // ReSharper disable DoNotCallOverridableMethodsInConstructor
124
            //Caliburn.Micro uses DisplayName for the view's title
125
            DisplayName = "Pithos+ Preferences";
126
            // ReSharper restore DoNotCallOverridableMethodsInConstructor
127

    
128
            _windowManager = windowManager;
129
            _events = events;
130

    
131
            Shell = shell;
132

    
133
            Settings = settings;
134
            Accounts = new ObservableConcurrentCollection<AccountViewModel>();
135

    
136

    
137
            var startupPath = Environment.GetFolderPath(Environment.SpecialFolder.Startup);
138
            _shortcutPath = Path.Combine(startupPath, "Pithos.lnk");
139

    
140

    
141
            StartOnSystemStartup = File.Exists(_shortcutPath);
142

    
143
            //SelectedTab = currentTab;
144
        }
145

    
146
        protected override void OnViewLoaded(object view)
147
        {
148
            base.OnViewLoaded(view);
149

    
150
            Settings.Reload();
151

    
152
            Accounts.Clear();
153

    
154
            if (Settings.Accounts == null)
155
            {
156
                Settings.Accounts = new AccountsCollection();
157
                Settings.Save();
158
            }
159
            var accountVMs = from account in Settings.Accounts
160
                             select new AccountViewModel(account);
161

    
162
            Accounts.AddFromEnumerable(accountVMs);
163
            if (Accounts.Count > 0)
164
                CurrentAccount = Accounts.First();
165

    
166
        }
167

    
168
        private string _selectedTab = "General";
169

    
170
        public string SelectedTab
171
        {
172
            get { return _selectedTab; }
173
            set
174
            {
175
                _selectedTab = value ?? "GeneralTab";
176
                NotifyOfPropertyChange(() => SelectedTab);
177
                NotifyOfPropertyChange(() => AccountTabSelected);
178
            }
179
        }
180

    
181

    
182
        public bool AccountTabSelected
183
        {
184
            get { return _selectedTab == "AccountTab"; }
185
        }
186

    
187
        #region Preferences Properties
188

    
189
        private bool _noProxy;
190

    
191
        public bool NoProxy
192
        {
193
            get { return _noProxy; }
194
            set
195
            {
196
                _noProxy = value;
197
                NotifyOfPropertyChange(() => NoProxy);
198
            }
199
        }
200

    
201

    
202
        private bool _defaultProxy;
203

    
204
        public bool DefaultProxy
205
        {
206
            get { return _defaultProxy; }
207
            set
208
            {
209
                _defaultProxy = value;
210
                NotifyOfPropertyChange(() => DefaultProxy);
211
            }
212
        }
213

    
214

    
215
        private bool _manualProxy;
216

    
217
        public bool ManualProxy
218
        {
219
            get { return _manualProxy; }
220
            set
221
            {
222
                _manualProxy = value;
223
                NotifyOfPropertyChange(() => ManualProxy);
224
            }
225
        }
226

    
227
        #endregion
228

    
229

    
230
        public int StartupDelay
231
        {
232
            get { return (int) Settings.StartupDelay.TotalMinutes; }
233
            set
234
            {
235
                if (value < 0)
236
                    throw new ArgumentOutOfRangeException("value",
237
                                                          Resources.
238
                                                              PreferencesViewModel_StartupDelay_Greater_or_equal_to_0);
239
                Settings.StartupDelay = TimeSpan.FromMinutes(value);
240
                NotifyOfPropertyChange(() => StartupDelay);
241
            }
242
        }
243

    
244
        #region Commands
245

    
246
        public bool CanSelectiveSyncFolders
247
        {
248
            get { return CurrentAccount != null && CurrentAccount.SelectiveSyncEnabled; }
249
        }
250

    
251
        public void SelectiveSyncFolders()
252
        {
253
            //var monitor = Shell.Monitors[CurrentAccount.AccountKey];
254

    
255

    
256
            var model = new SelectiveSynchViewModel(_events, CurrentAccount.Account, CurrentAccount.ApiKey, false);
257
            if (_windowManager.ShowDialog(model) == true)
258
            {
259

    
260
            }
261
        }
262

    
263
        /* private bool _networkTracing;
264
        public bool NetworkTracing
265
        {
266
            get { return _networkTracing; }
267
            set
268
            {
269
                _networkTracing = value;
270
                
271
            }
272
        }*/
273

    
274
        public void RefreshApiKey()
275
        {
276
            //_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 });
277
            if (CurrentAccount == null)
278
                return;
279
            try
280
            {
281

    
282
                var name = CurrentAccount.AccountName;
283

    
284
                var loginUri = new Uri(CurrentAccount.ServerUrl).Combine("login");
285
                var credentials = PithosAccount.RetrieveCredentials(loginUri.ToString(), name);
286
                if (credentials == null)
287
                    return;
288
                //The server will return credentials for a different account, not just the current account
289
                //We need to find the correct account first
290
                AccountViewModel account=null;
291
                Guid token;
292
                if (Guid.TryParse(name, out token))
293
                {
294
                    account =
295
                        Accounts.First(
296
                            act => act.AccountName == credentials.UserName && act.ServerUrl == CurrentAccount.ServerUrl);
297
                }
298
                else
299
                {
300
                    account =
301
                        Accounts.First(
302
                            act => act.AccountName == name && act.ServerUrl == CurrentAccount.ServerUrl);
303
                    account.AccountName = credentials.UserName;
304

    
305
                }
306
                account.ApiKey = credentials.Password;
307
                account.IsExpired = false;
308
                Settings.Save();
309
                TaskEx.Delay(10000).ContinueWith(_ => Shell.MonitorAccount(account.Account));
310
                NotifyOfPropertyChange(() => Accounts);
311
            }
312
            catch (AggregateException exc)
313
            {
314
                string message = String.Format("API Key retrieval failed");
315
                Log.Error(message, exc.InnerException);
316
                _events.Publish(new Notification
317
                                    {Title = "Authorization failed", Message = message, Level = TraceLevel.Error});
318
            }
319
            catch (Exception exc)
320
            {
321
                string message = String.Format("API Key retrieval failed");
322
                Log.Error(message, exc);
323
                _events.Publish(new Notification
324
                                    {Title = "Authorization failed", Message = message, Level = TraceLevel.Error});
325
            }
326

    
327
        }
328

    
329
        public bool CanWipeAccount
330
        {
331
            get { return CurrentAccount != null 
332
                && Shell.Monitors.ContainsKey(CurrentAccount.AccountKey)
333
                && Shell.Monitors[CurrentAccount.AccountKey].CloudClient!=null;
334
            }
335
        }
336

    
337
        public async void WipeAccount()
338
        {
339
            PithosMonitor aMonitor;
340
            if (Shell.Monitors.TryGetValue(CurrentAccount.AccountKey, out aMonitor))
341
            {
342
                if (aMonitor.CloudClient == null)
343
                {
344
                    Log.ErrorFormat("Tried to wipe account [{0}] before authenticating",CurrentAccount.AccountKey);
345
                    return;
346
                }
347
                var message = String.Format("You are about to wipe all data in the {0} account at {1}. Are you sure?",
348
                                            CurrentAccount.AccountName, CurrentAccount.ServerUrl);
349
                if (MessageBoxResult.Yes !=
350
                    MessageBox.Show(message, "Warning! Account data will be wiped", MessageBoxButton.YesNo,
351
                                    MessageBoxImage.Hand, MessageBoxResult.No))
352
                    return;      
353
                          
354
                await aMonitor.CloudClient.WipeContainer("", new Uri("pithos", UriKind.Relative));
355
                aMonitor.Stop();
356
                await aMonitor.Start();
357
                MessageBox.Show("Account wiped");
358
            }
359
        }
360

    
361

    
362
        public void OpenLogPath()
363
        {
364
            Shell.OpenLogPath();
365
        }
366

    
367
        public void OpenLogConsole()
368
        {
369
            var logView = IoC.Get<LogConsole.LogConsoleViewModel>();
370
            _windowManager.ShowWindow(logView);
371
        }
372

    
373
        public void SaveChanges()
374
        {
375
            DoSave();
376
            TryClose( /*true*/);
377
        }
378

    
379
        public void RejectChanges()
380
        {
381
            Settings.Reload();
382
            TryClose( /*false*/);
383
        }
384

    
385
        public void ApplyChanges()
386
        {
387
            DoSave();
388
        }
389

    
390
        private void DoSave()
391
        {
392
            //SetStartupMode();            
393

    
394
            //Ensure we save the settings changes first
395
            foreach (var account in _accountsToRemove)
396
            {
397
                Settings.Accounts.Remove(account);
398
            }
399

    
400
            foreach (var account in _accountsToAdd)
401
            {
402
                Settings.Accounts.Add(account);
403
            }
404

    
405
            Settings.Save();
406

    
407

    
408
            try
409
            {
410
                foreach (var account in _accountsToRemove)
411
                {
412
                    Shell.RemoveMonitor(account.ServerUrl, account.AccountName);
413
                    Shell.RemoveAccountFromDatabase(account);
414
                }
415

    
416
                foreach (var account in Settings.Accounts)
417
                {
418
                    Shell.MonitorAccount(account);
419
                }
420

    
421
                var poller = IoC.Get<PollAgent>();
422
                poller.SynchNow();
423
            }
424
            finally
425
            {
426
                _accountsToRemove.Clear();
427
                _accountsToAdd.Clear();
428
            }
429

    
430
            NotifyOfPropertyChange(() => Settings);
431

    
432
            if (IgnoreCertificateErrors)
433
                ServicePointManager.ServerCertificateValidationCallback = (sender, certificate, chain, errors) => true;
434
            else
435
            {
436
                ServicePointManager.ServerCertificateValidationCallback = null;
437
            }
438
        }
439

    
440
        /*   public void ChangePithosFolder()
441
        {
442
            var browser = new FolderBrowserDialog();
443
            browser.SelectedPath = Settings.PithosPath;
444
            var result = browser.ShowDialog((IWin32Window)GetView());
445
            if (result == DialogResult.OK)
446
            {
447
                var newPath = browser.SelectedPath;
448
                var accountName = CurrentAccount.AccountName;
449
                var monitor = Shell.Monitors[accountName];
450
                monitor.Stop();
451
                
452
                Shell.Monitors.Remove(accountName);
453

    
454
                Directory.Move(Settings.PithosPath, newPath);
455
                Settings.PithosPath = newPath;
456
                Settings.Save();
457

    
458
                Shell.MonitorAccount(CurrentAccount);
459

    
460
                NotifyOfPropertyChange(() => Settings);                
461
            }
462
        }
463
*/
464

    
465

    
466
        private readonly List<AccountSettings> _accountsToAdd = new List<AccountSettings>();
467

    
468
        public async void AddAccount()
469
        {
470
            var wizard = new AddAccountViewModel();
471
            if (_windowManager.ShowDialog(wizard) == true)
472
            {
473
                try
474
                {
475
                    string selectedPath = wizard.AccountPath;
476
                    var initialRootPath = wizard.ShouldCreateOkeanosFolder
477
                                              ? Path.Combine(selectedPath, "okeanos")
478
                                              : selectedPath;
479
                    var actualRootPath = initialRootPath;
480
                    if (wizard.ShouldCreateOkeanosFolder)
481
                    {
482
                        int attempt = 1;
483
                        while (Directory.Exists(actualRootPath) || File.Exists(actualRootPath))
484
                        {
485
                            actualRootPath = String.Format("{0} {1}", initialRootPath, attempt++);
486
                        }
487
                        Directory.CreateDirectory(actualRootPath);
488
                    }
489

    
490

    
491

    
492
                    var account =
493
                        Accounts.FirstOrDefault(
494
                            act => act.AccountName == wizard.AccountName && act.ServerUrl == wizard.CurrentServer);
495
                    if (account != null)
496
                    {
497
                        if (
498
                            MessageBox.Show("The account you specified already exists. Do you want to update it?",
499
                                            "The account exists") == MessageBoxResult.Yes)
500
                        {
501
                            account.ApiKey = wizard.Token;
502
                            account.IsExpired = false;
503
                            CurrentAccount = account;
504
                        }
505
                    }
506
                    else
507
                    {
508
                        var newAccount = new AccountSettings
509
                                             {
510
                                                 AccountName = wizard.AccountName,
511
                                                 ServerUrl = wizard.CurrentServer,
512
                                                 ApiKey = wizard.Token,
513
                                                 RootPath = actualRootPath,
514
                                                 IsActive = wizard.IsAccountActive,
515
                                             };
516

    
517
                        
518
                        var client = new CloudFilesClient(newAccount.AccountName, newAccount.ApiKey)
519
                                         {
520
                                             AuthenticationUrl = newAccount.ServerUrl,
521
                                             UsePithos = true
522
                                         };
523
                        await client.Authenticate().ConfigureAwait(false);
524

    
525
                        Guid token;
526
                        if (Guid.TryParse(wizard.AccountName, out token))
527
                        {
528
                            newAccount.AccountToken = token;
529
                            newAccount.DisplayName = await client.ResolveName(token).ConfigureAwait(false);    
530
                        }
531

    
532
                        
533
                        await InitializeSelectiveFolders(newAccount, client);
534

    
535

    
536
                        //TODO:Add the "pithos" container as a default selection                   
537

    
538
                        _accountsToAdd.Add(newAccount);
539
                        var accountVm = new AccountViewModel(newAccount);
540
                        (Accounts as IProducerConsumerCollection<AccountViewModel>).TryAdd(accountVm);
541
                        CurrentAccount = accountVm;
542
                    }
543
                    NotifyOfPropertyChange(() => Accounts);
544
                    NotifyOfPropertyChange(() => Settings);
545
                }
546
                catch (WebException exc)
547
                {
548
                    Log.ErrorFormat("[Add Account] Connectivity Error: {0}", exc);
549
                    MessageBox.Show("Unable to connect to Pithos. Please try again later", "Connectivity Error",
550
                                    MessageBoxButton.OK, MessageBoxImage.Exclamation);
551
                }
552
            }
553

    
554

    
555

    
556
        }
557

    
558
        private async Task InitializeSelectiveFolders(AccountSettings newAccount, CloudFilesClient client,
559
                                                      int retries = 3)
560
        {
561
            while (true)
562
            {
563
                try
564
                {
565
                    
566

    
567
                    var containers = await client.ListContainers(newAccount.AccountName).ConfigureAwait(false);
568
                    var containerUris = from container in containers
569
                                        select String.Format(@"{0}/v1/{1}/{2}",
570
                                                             newAccount.ServerUrl, newAccount.AccountName,
571
                                                             container.Name);
572
                    lock (newAccount.SelectiveFolders)
573
                    {
574
                        newAccount.SelectiveFolders.AddRange(containerUris.ToArray());
575
                    }
576

    
577
                    var objectInfos = (from container in containers
578
                                       from dir in client.ListObjects(newAccount.AccountName, container.Name)
579
                                       where container.Name.ToString() != "trash"
580
                                       select dir).ToList();
581
                    var tree = objectInfos.ToTree();
582

    
583
                    var selected = (from root in tree
584
                                    from child in root
585
                                    select child.Uri.ToString()).ToArray();
586
                    lock (newAccount.SelectiveFolders)
587
                    {
588
                        newAccount.SelectiveFolders.AddRange(selected);
589
                    }
590
                    return;
591
                }
592
                catch (WebException)
593
                {
594
                    if (retries > 0)
595
                        retries--;
596
                    else
597
                        throw;
598
                }
599
            }
600
        }
601

    
602
/*
603
        public void AddPithosAccount()
604
       {
605
            var credentials=PithosAccount.RetrieveCredentials(null);
606
            if (credentials == null)
607
                return;
608
            var account = Settings.Accounts.FirstOrDefault(act => act.AccountName == credentials.UserName);
609
            var accountVM = new AccountViewModel(account);
610
            if (account == null)
611
            {
612
                account=new AccountSettings{
613
                    AccountName=credentials.UserName,
614
                    ApiKey=credentials.Password
615
                };
616
                Settings.Accounts.Add(account);
617
                accountVM = new AccountViewModel(account);
618
                (Accounts as IProducerConsumerCollection<AccountViewModel>).TryAdd(accountVM);
619
            }
620
            else
621
            {
622
                account.ApiKey=credentials.Password;
623
            }
624
            //SelectedAccountIndex= Settings.Accounts.IndexOf(account);
625
            CurrentAccount = accountVM;
626
            NotifyOfPropertyChange(() => Accounts);
627
            NotifyOfPropertyChange(()=>Settings);                       
628
       }
629
*/
630

    
631

    
632
        private readonly List<AccountSettings> _accountsToRemove = new List<AccountSettings>();
633

    
634
        public void RemoveAccount()
635
        {
636
            Accounts.TryRemove(CurrentAccount);
637
            _accountsToRemove.Add(CurrentAccount.Account);
638

    
639
            CurrentAccount = null;
640
            NotifyOfPropertyChange(() => Accounts);
641

    
642

    
643
            //NotifyOfPropertyChange("Settings.Accounts");
644
        }
645

    
646
        public bool CanRemoveAccount
647
        {
648
            get { return (CurrentAccount != null); }
649
        }
650

    
651
        public bool CanClearAccountCache
652
        {
653
            get { return (CurrentAccount != null); }
654
        }
655

    
656
        public void ClearAccountCache()
657
        {
658
            if (MessageBoxResult.Yes ==
659
                MessageBox.Show("You are about to delete all partially downloaded files from the account's cache.\n" +
660
                                " You will have to download all partially downloaded data again\n" +
661
                                "This change can not be undone\n\n" +
662
                                "Do you wish to delete all partially downloaded data?",
663
                                "Warning! Clearing account cache",
664
                                MessageBoxButton.YesNo, MessageBoxImage.Question, MessageBoxResult.No))
665
            {
666

    
667
                var cachePath = Path.Combine(CurrentAccount.RootPath, FolderConstants.CacheFolder);
668
                var dir = new DirectoryInfo(cachePath);
669
                //The file may not exist if we just created the account
670
                if (!dir.Exists)
671
                    return;
672
                dir.EnumerateFiles().Apply(file => file.Delete());
673
                dir.EnumerateDirectories().Apply(folder => folder.Delete(true));
674
            }
675
        }
676

    
677

    
678
        public bool ExtensionsActivated
679
        {
680
            get { return Settings.ExtensionsActivated; }
681
            set
682
            {
683
                if (Settings.ExtensionsActivated == value)
684
                    return;
685

    
686
                Settings.ExtensionsActivated = value;
687

    
688
/*
689
                if (value)
690
                    _extensionController.RegisterExtensions();
691
                else
692
                {
693
                    _extensionController.UnregisterExtensions();
694
                }
695
*/
696
                NotifyOfPropertyChange(() => ExtensionsActivated);
697
            }
698
        }
699

    
700
        public bool DebugLoggingEnabled
701
        {
702
            get { return Settings.DebugLoggingEnabled; }
703
            set
704
            {
705
                Settings.DebugLoggingEnabled = value;
706
                NotifyOfPropertyChange(() => DebugLoggingEnabled);
707
            }
708
        }
709

    
710
        public bool IgnoreCertificateErrors
711
        {
712
            get { return Settings.IgnoreCertificateErrors; }
713
            set
714
            {
715
                Settings.IgnoreCertificateErrors = value;
716
                NotifyOfPropertyChange(() => IgnoreCertificateErrors);
717
            }
718
        }
719

    
720
        #endregion
721

    
722
        /* private int _selectedAccountIndex;
723
        public int SelectedAccountIndex
724
        {
725
            get { return _selectedAccountIndex; }
726
            set
727
            {
728
                //var accountCount=Settings.Accounts.Count;
729
                //if (accountCount == 0)
730
                //    return;
731
                //if (0 <= value && value < accountCount)
732
                //    _selectedAccountIndex = value;
733
                //else
734
                //    _selectedAccountIndex = 0;
735
                _selectedAccountIndex = value;
736
                NotifyOfPropertyChange(() => CurrentAccount);
737
                NotifyOfPropertyChange(() => CanRemoveAccount);
738
                NotifyOfPropertyChange(()=>SelectedAccountIndex);
739
            }
740
        }*/
741

    
742
        private AccountViewModel _currentAccount;
743
        private readonly IWindowManager _windowManager;
744
        private readonly string _shortcutPath;
745

    
746

    
747

    
748
        public AccountViewModel CurrentAccount
749
        {
750
            get { return _currentAccount; }
751
            set
752
            {
753
                _currentAccount = value;
754

    
755
                if (_currentAccount != null)
756
                    _currentAccount.PropertyChanged += (o, e) => NotifyOfPropertyChange(() => CanSelectiveSyncFolders);
757

    
758
                NotifyOfPropertyChange(() => CurrentAccount);
759
                NotifyOfPropertyChange(() => CanRemoveAccount);
760
                NotifyOfPropertyChange(() => CanSelectiveSyncFolders);
761
                NotifyOfPropertyChange(() => CanMoveAccountFolder);
762
                NotifyOfPropertyChange(() => CanClearAccountCache);
763
                NotifyOfPropertyChange(() => CanWipeAccount);
764
            }
765
        }
766

    
767
/*
768
        public AccountSettings CurrentAccount
769
        {
770
            get {
771
                if (0 <= SelectedAccountIndex && SelectedAccountIndex < Settings.Accounts.Count)                    
772
                    return Settings.Accounts[SelectedAccountIndex];
773
                return null;
774
            }
775

    
776
        }
777
*/
778

    
779

    
780
        public bool CanMoveAccountFolder
781
        {
782
            get { return CurrentAccount != null; }
783
        }
784

    
785
        public void MoveAccountFolder()
786
        {
787

    
788
            using (var dlg = new FolderBrowserDialog())
789
            {
790
                var currentFolder = CurrentAccount.RootPath;
791
                dlg.SelectedPath = currentFolder;
792
                //Ask the user to select a folder
793
                //Note: We need a parent window here, which we retrieve with GetView            
794
                var view = (Window) GetView();
795
                if (DialogResult.OK != dlg.ShowDialog(new Wpf32Window(view)))
796
                    return;
797

    
798
                var newPath = dlg.SelectedPath;
799
                //Find the account's monitor and stop it
800
                PithosMonitor monitor;
801
                if (Shell.Monitors.TryGetValue(CurrentAccount.AccountKey, out monitor))
802
                {
803
                    //Problem: Doesn't stop the poll agent
804
                    monitor.Stop();
805

    
806
                    monitor.MoveRootFolder(newPath);
807

    
808
                   
809
                }
810
                //Replace the old rootpath with the new
811
                CurrentAccount.RootPath = newPath;
812
                //TODO: This will save all settings changes. Too coarse grained, need to fix at a later date
813
                Settings.Save();
814
                //And start the monitor on the new RootPath            
815
                if (monitor != null)
816
                {
817
                    monitor.RootPath = newPath;
818
                    if (CurrentAccount.IsActive)
819
                        Shell.StartMonitor(monitor);
820
                        
821
                }
822
                else
823
                    Shell.MonitorAccount(CurrentAccount.Account);
824
                //Finally, notify that the Settings, CurrentAccount have changed
825
                NotifyOfPropertyChange(() => CurrentAccount);
826
                NotifyOfPropertyChange(() => Settings);
827

    
828
            }
829
        }
830

    
831
    }
832
}