using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
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 System.Collections.ObjectModel;
using Telerik.ReportViewer.Silverlight;

namespace RetrieveDataFromSilverlight
{
    public partial class MainPage : UserControl
    {
        private ServiceReference1.Service2Client myService;
        string paramVal;

        public MainPage()
        {
            InitializeComponent();
            //listen for this event in order to be able to change the parameters values
            this.reportViewer1.RenderBegin += new RenderBeginEventHandler(reportViewer1_RenderBegin);

            myService = new ServiceReference1.Service2Client();
            myService.PostDataCompleted += new EventHandler<System.ComponentModel.AsyncCompletedEventArgs>(myService_PostDataCompleted);
            myService.GetDataCompleted += new EventHandler<ServiceReference1.GetDataCompletedEventArgs>(myService_GetDataCompleted);
        }

        void reportViewer1_RenderBegin(object sender, RenderBeginEventArgs args)
        {
            //add the parameters values here
            args.ParameterValues["Param"] = this.paramVal;
        }
        
        private void buttonSend_Click(object sender, RoutedEventArgs e)
        {
            List<string> words = new List<string>(this.textBox.Text.Split(' '));
            myService.PostDataAsync(words);
        }

        private void button1_Click(object sender, RoutedEventArgs e)
        {
            this.paramVal = this.paramTextBox.Text;
            this.reportViewer1.RefreshReport();
        }

        void myService_PostDataCompleted(object sender, System.ComponentModel.AsyncCompletedEventArgs e)
        {
            myService.GetDataAsync();
            this.reportViewer1.RefreshReport();
        }

        void myService_GetDataCompleted(object sender, ServiceReference1.GetDataCompletedEventArgs e)
        {
            textBox.Text = string.Empty;
            var data = e.Result;
            foreach (var item in data)
            {
                textBox.Text += item + " ";
            }
        }

    }

    static class ReportViewerExtensions
    {
        public static void RefreshReport(this ReportViewer reportViewer)
        {            
            var layoutRoot = (FrameworkElement)VisualTreeHelper.GetChild(reportViewer, 0);
            var viewerModel = (ReportViewerModel)layoutRoot.DataContext;
            var refreshCommand = viewerModel.RefreshReportCommand;
            if (refreshCommand.CanExecute(null))
            {
                refreshCommand.Execute(null);
            }
        }
    }

}
