using System; using System.Linq; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Windows; using System.Windows.Controls; using System.Windows.Input; using Juick.Classes; using JuickApi; using RestSharp; using Microsoft.Phone.Controls; namespace Juick.ViewModels { public class PageViewModel : ViewModelBase { public PageViewModel(AppViewModel context) { _context = context; Items = new ObservableCollection(); LoadMessagesPageCommand = new DelegateCommand(CheckNewData, () => !context.IsDataLoading); NavigateNextCommand = new DelegateCommand(NavigateToThread, () => true); } private readonly AppViewModel _context; private string _restUri; public string RestUri { get { return _restUri; } set { _restUri = value; } } public virtual string Caption { get; set; } public ObservableCollection Items { get; private set; } public DelegateCommand LoadMessagesPageCommand { get; private set; } public DelegateCommand NavigateNextCommand { get; private set; } public void NavigateToThread(GestureEventArgs param) { PostItem post = ((FrameworkElement)param.OriginalSource).DataContext as PostItem; if (post != null) ((App)Application.Current).NavigateTo( new Uri(string.Format("/ThreadView.xaml?mid={0}", post.MID), UriKind.Relative)); } public void CheckNewData(ItemRealizationEventArgs e) { const int offset = 5; if (e == null) return; var item = e.Container.Content; if (item.Equals(Items[Items.Count - offset])) { RefreshData(); } } public void RefreshData() { var requestUri = RestUri + "&rnd=" + Environment.TickCount; if (Items.Count > 0) { requestUri += string.Format("&before_mid={0}", Items[Items.Count - 1].MID); } var request = new RestRequest(requestUri); _context.Client.ExecuteAsync>(request, response => { _context.IsDataLoading = false; if (response == null || response.ErrorException != null) { return; } if (response.Data == null) return; response.Data.Select(x => new PostItem(x)).ToList().ForEach(i => Items.Add(i)); }); _context.IsDataLoading = true; } } }