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 ComboBoxDemo.Web;
using System.ServiceModel.DomainServices.Client;
using System.Threading;
using Telerik.Windows.Controls;

namespace ComboBoxDemo
{
    public partial class MainPage : UserControl
    {
        //private AdresarDomainContext domainContext = new AdresarDomainContext();
        private AdresarDomainContext domainContext = new AdresarDomainContext();
        private int activeOperationCount = 0;
        
        public MainPage()
        {
            InitializeComponent();

            domainContext.IsBusy += new EventHandler<IsBusyEventArgs>(domainContext_IsBusy);

            StartLoadData();
        }

        private void StartLoadData()
        {
            this.domainContext.Load(this.domainContext.GetOsobaByIdQuery(), OsobaLoadedCallback, null);

            this.domainContext.Load(
                    this.domainContext.GetPohlavisQuery(),
                    (lo) => { cbPohlavi.ItemsSource = lo.Entities; },
                    null);

            this.domainContext.Load(
                this.domainContext.GetUserNameQuery(),
                (ol) => { radButton1.Content = (ol.Entities.FirstOrDefault() as MyUser).UserName; },
                null);
        }           

        private void domainContext_IsBusy(object sender, IsBusyEventArgs e)
        {
            loadIndicator.IsBusy = e.IsBusy;
            if (e.IsBusy)
            {
                mainPanel.Opacity = 0;
            }
            else
            {
                mainPanel.Opacity = 100;
            }
        }

        void io_Completed(object sender, EventArgs e)
        {
            radButton1.Content = ((InvokeOperation<string>)sender).Value;            
        }

        private void OsobaLoadedCallback(LoadOperation<Osoba> loadOperation)
        {
            this.DataContext = loadOperation.Entities.FirstOrDefault();
            //TestBusyIndicator();
        }

        private void TestBusyIndicator()
        {
            Interlocked.Decrement(ref activeOperationCount);
            if (activeOperationCount == 0)
            {
                loadIndicator.IsBusy = false;
            }
        }

        private void radButton1_Click(object sender, RoutedEventArgs e)
        {
            Osoba osoba = this.DataContext as Osoba;
            //Osoba osoba = ds.CurrentItem as Osoba;
            MessageBox.Show(osoba.Pohlavi.Nazev);

            
            this.domainContext.SubmitChanges();
        }

        private void radButton2_Click(object sender, RoutedEventArgs e)
        {
            StartLoadData();
        }
    }
}
