using System;
using System.Windows;

using BS.Shared.Core;
using BS.Shared.DataContracts.Compact;

namespace BeWo.View.Controls
{
    public partial class CustomerSelectionControl
    {
        private CompactCustomerDC mSelectedCustomerDC;

        public CustomerSelectionControl()
        {
            InitializeComponent();
        }

        public event EventHandler ControlInitialized;

        public event EventHandler<EventArgs<CompactCustomerDC>> ItemSelected;

        public CompactCustomerDC SelectedItem
        {
            get { return mSelectedCustomerDC; }
            set
            {
                mSelectedCustomerDC = value;
                UpdateControls();
            }
        }

        public string SearchText
        {
            get { return SearchView.SearchText; }
            set { SearchView.SearchText = value; }
        }

        private void CustomerSearchView_ItemSelected(object sender, EventArgs<CompactCustomerDC> e)
        {
            popupCustomers.IsOpen = false;
            SetSelectedCustomer(e.Data);
        }

        private void SetSelectedCustomer(CompactCustomerDC dc)
        {
            mSelectedCustomerDC = dc;

            UpdateControls();

            if (ItemSelected != null)
                ItemSelected(this, new EventArgs<CompactCustomerDC>(mSelectedCustomerDC));
        }

        private void UpdateControls()
        {
            img.Visibility = mSelectedCustomerDC == null ? Visibility.Collapsed : Visibility.Visible;
            if (ItemContent != null)
                ItemContent.DataContext = mSelectedCustomerDC;
        }

        private void btnSelectCustomer_Click(object sender, RoutedEventArgs e)
        {
            popupCustomers.IsOpen = true;
        }

        internal void SetSelectedCustomerOid(long pOid)
        {
            var items = SearchView.Customers;

            if (items == null || items.Count == 0) { }

            if (items != null)
            {
                CompactCustomerDC found = null;

                foreach (var sc in items)
                    if (found == null)
                        if (sc != null && sc.CustomerOid == pOid)
                            found = sc;

                if (found != null)
                    SetSelectedCustomer(found);
            }
        }
    }
}
