using System; using System.Linq; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Net; using System.Windows; using Juick.Classes; using JuickApi; using RestSharp; using Microsoft.Phone.Controls; using System.Windows.Controls; namespace Juick.ViewModels { public class PageViewModel : ViewModelBase { public PageViewModel(AppViewModel context) { _context = context; Items = new ObservableCollection(); LoadMessagesPageCommand = new DelegateCommand(LoadData, () => !context.IsDataLoading); NavigateNextCommand = new DelegateCommand(NavigateToThread, () => true); } private readonly AppViewModel _context; public string RestUri { get; set; } public virtual string Caption { get { return "juick"; } } /// /// A collection for MessageViewModel objects. /// public ObservableCollection Items { get; private set; } public DelegateCommand LoadMessagesPageCommand { get; private set; } public DelegateCommand NavigateNextCommand { get; private set; } public void NavigateToThread(SelectionChangedEventArgs param) { if (param != null) { ((App)App.Current).NavigateTo(new Uri(string.Format("/ThreadView.xaml?mid={0}", ((PostItem)param.AddedItems[0]).MID), UriKind.Relative)); } } /// /// Creates and adds a few MessageViewModel objects into the Items collection. /// public void LoadData(LinkUnlinkEventArgs e) { const int offset = 5; if (_context.IsDataLoading) { return; } if (e != null) { var item = e.ContentPresenter.Content; if (!item.Equals(Items[Items.Count - offset])) { return; } } if (string.IsNullOrEmpty(RestUri)) { RestUri = "/home?1=1"; } // super-костыли // todo: rewrite else if (RestUri.StartsWith("/home?", StringComparison.InvariantCulture) && Items.Count > 0) { var lastItem = Items[Items.Count - 1]; RestUri = string.Format("/home?before_mid={0}", lastItem.MID); } else if (RestUri.StartsWith("/messages?", StringComparison.InvariantCulture) && Items.Count > 0) { var lastItem = Items[Items.Count - 1]; RestUri = string.Format("/messages?before_mid={0}", lastItem.MID); } var request = new RestRequest(RestUri + "&rnd=" + Environment.TickCount); _context.Client.Authenticator = new HttpBasicAuthenticator(_context.Account.Credentials.UserName, _context.Account.Credentials.Password); _context.Client.ExecuteAsync>(request, ProcessResponse); _context.IsDataLoading = true; } void ProcessResponse(IRestResponse> response) { _context.IsDataLoading = false; if (response.StatusCode != HttpStatusCode.OK) { MessageBox.Show(response.StatusCode.ToString()); return; } //Items.Clear(); response.Data.Select(x => new PostItem(x)).ToList().ForEach(i => Items.Add(i)); } } }