using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Runtime.Serialization.Json;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using TFC_ClientApp.Models;

namespace TFC_ClientApp
{
    public partial class MainPage : PhoneApplicationPage
    {
        // Constructor
        public MainPage()
        {
            InitializeComponent();
        }
        
        WebClient proxy;
        User user = new User();

        private void GetData()
        {
            string url = (Application.Current.Resources["URI_SERVER"] as String)+ "GetUser/" + this.textBoxUsername.Text + "/" + this.textBoxPass.Password;

            proxy = new WebClient();
            proxy.OpenReadCompleted += new OpenReadCompletedEventHandler(proxy_OpenReadCompleted);
            Uri uri = new Uri(url, UriKind.Absolute);

            proxy.OpenReadAsync(uri);
        }

        void proxy_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
        {
            if (e.Error == null)
            {
                Stream strm = e.Result;
                DataContractJsonSerializer s = new DataContractJsonSerializer(typeof(User));
                User user = s.ReadObject(strm) as User;
                this.user = user;
                NavigationService.Navigate(new Uri("/PivotPage1.xaml", UriKind.Relative));
            }
            else
            {
                MessageBox.Show("Usuario no válido", "Vuelva a intentarlo", MessageBoxButton.OK);
            }
        }

        private void button1_Click(object sender, RoutedEventArgs e)
        {
            GetData();
        }

        protected override void OnNavigatedFrom(System.Windows.Navigation.NavigationEventArgs e)
        {
            
            base.OnNavigatedFrom(e);

            PivotPage1 pivot = e.Content as PivotPage1;

            if (pivot != null)
            {
                pivot.DataContext = user;
            }
        }
    }
}