using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using System.ServiceModel.Channels;
using System.Threading.Tasks;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Popups;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
using Microsoft.WindowsAzure.MobileServices;
using UmkSamples.Model;

// The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238

namespace UmkSamples.View
{
    /// <summary>
    /// An empty page that can be used on its own or navigated to within a Frame.
    /// </summary>
    public sealed partial class AzurePage : Page
    {
        public AzurePage()
        {
            this.InitializeComponent();
            RefreshTable();
        }

        private async void RefreshTable()
        {
            await RefreshTodoItems();
        }

        private void CheckBoxComplete_Checked(object sender, RoutedEventArgs e)
        {
            throw new NotImplementedException();
        }

        private async Task InsertTodoItem(TodoItem todoItem)
        {
            await App.MobileService.GetTable<TodoItem>().InsertAsync(todoItem);
            //await App.MobileService.GetTable<TodoItem>().ToListAsync();

            await App.MobileService.GetTable<TodoItem>().UpdateAsync(todoItem);
            await App.MobileService.GetTable<TodoItem>().DeleteAsync(todoItem);
            //await SyncAsync(); // offline sync
        }

        private async Task RefreshTodoItems()
        {
            try
            {
                // This code refreshes the entries in the list view by querying the TodoItems table.
                // The query excludes completed TodoItems
                var items = await App.MobileService.GetTable<TodoItem>().Where(todoItem => todoItem.Complete == false)
                    .ToCollectionAsync();
                var md = new MessageDialog(items.Count.ToString());
                await md.ShowAsync();
                ListItems.ItemsSource = items;
            }
            catch (MobileServiceInvalidOperationException e)
            {
                var md = new MessageDialog("Error, try again.");
                md.ShowAsync();
            }
        }
    }
}
