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 WorkoutPage : PhoneApplicationPage
    {
        private WebClient proxy;
        private List<Models.Workout> workouts;
        private String userId;
        private String dateWorkout;

        public WorkoutPage()
        {
            InitializeComponent();
            this.Loaded += (sender, e) =>
            {
                GetData();
            };    
        }

        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {

            NavigationContext.QueryString.TryGetValue("selectedItem", out dateWorkout);
            userId = dateWorkout.Split('|')[1];
            dateWorkout = dateWorkout.Split('|')[0];
            dateWorkout = dateWorkout.Replace('/', '-').Remove(10);
            PageTitle.Text = dateWorkout;
            
        }

        private void GetData()
        {

            string url = (Application.Current.Resources["URI_SERVER"] as String) + "/GetWorkoutsByDateAndUserId/" + userId + "/" + dateWorkout;

            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(List<Workout>));
                workouts = s.ReadObject(strm) as List<Models.Workout>;

                this.MainListBox.ItemsSource = workouts;

            }
            else
            {
                MessageBox.Show("Ha ocurrido un error", "Vuelva a intentarlo", MessageBoxButton.OK);
            }
        }

        private void MainListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            // Si el índice seleccionado es -1 (no hay selección) no hacer nada
            if (MainListBox.SelectedIndex == -1)
                return;

            Workout workout =(Workout) MainListBox.SelectedValue;
            // Navegar a la página siguiente
            NavigationService.Navigate(new Uri(string.Format("/WorkoutEditPage.xaml?selectedItem={0}|{1}|{2}|{3}|{4}|{5}|{6}", workout.WorkoutID, workout.Exercice.Name, workout.Series, workout.Load, workout.Repetitions, workout.Pause, workout.IsRealized), UriKind.Relative));

            // Restablecer el índice seleccionado en -1 (no hay selección)
            MainListBox.SelectedIndex = -1;
        }
   
    }
}