using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.ServiceModel;
using System.Diagnostics;
using WPF_Sample.Common;

namespace WPF_Sample.Views.Examples
{
    /// <summary>
    /// Interaction logic for Example.xaml
    /// </summary>
    public partial class UserInfo : Page
    {
        #region Memebers

        private Stopwatch _stopwatch = new Stopwatch();
        private string _processingHistory = string.Empty;

        #endregion

        #region Constructor

        public UserInfo()
        {
            InitializeComponent();
            radioEmployeeID.IsChecked = true;
        }

        #endregion

        #region Private Methods

        private void loadDataGrid(IEnumerable<object> items)
        {
            dataGrid1.ItemsSource = items;
            if (dataGrid1.Items.IsEmpty)
            {
                borderNoRecords.Visibility = System.Windows.Visibility.Visible;
            }
            else
            {
                borderNoRecords.Visibility = System.Windows.Visibility.Hidden;
            }
        }

        private void loadDataGrid_V2(List<STWS_V2.GetUserDetailModel> getUserDetailModels)
        {
            List<STWS_V2.UserProfile> userList = new List<STWS_V2.UserProfile>();
            foreach (STWS_V2.GetUserDetailModel model in getUserDetailModels)
            {
                userList.Add(model.Profile);
            }

            dataGrid1.ItemsSource = userList;
            if (dataGrid1.Items.IsEmpty)
            {
                borderNoRecords.Visibility = System.Windows.Visibility.Visible;
            }
            else
            {
                borderNoRecords.Visibility = System.Windows.Visibility.Hidden;
            }
        }

        private void startTimer()
        {
            _stopwatch.Reset();
            _stopwatch.Start();
            _processingHistory = (lblProcessing.Content  == null) ? "" : lblProcessing.Content.ToString();
            lblProcessing.Content = "Loading...  Please Wait...";
            AppUtil.DoEvents();
        }

        private void endTimer()
        {
            _stopwatch.Stop();
            lblProcessing.Content = String.Format("Processed '{0}' records in '{1}' seconds", (dataGrid1.Items.Count).ToString(), _stopwatch.Elapsed.TotalSeconds);
        }

        private void routeServiceCall(bool getAll = false)
        {
            try
            {
                startTimer();
                //GET ALL
                if (getAll)
                {
                    userInfoGetAll();
                }

                //GET BY EMPLOYEE ID
                else if (radioEmployeeID.IsChecked == true)
                {
                    int Num;
                    bool isNum = int.TryParse(txtSearchData.Text, out Num);
                    if (!isNum)
                    {
                        MessageBox.Show("Please provide a valid number for the Employee ID", "Data Exception", MessageBoxButton.OK, MessageBoxImage.Information);
                        return;
                    }
                    userInfoGetByEmployeeID();
                }

                //GET BY EFFECTIVE DATE
                else if (radioLName.IsChecked == true)
                {
                    userInfoGetByLName();
                }
                endTimer();

            }
            catch (FaultException<STWS_V2.ServiceException> fe)
            {
                MessageBox.Show(fe.Detail.Message, "Service Exception", MessageBoxButton.OK, MessageBoxImage.Warning);
            }
            catch (FaultException<STWS.ServiceException> fe)
            {
                MessageBox.Show(fe.Detail.Message, "Service Exception", MessageBoxButton.OK, MessageBoxImage.Warning);
            }
            catch (EndpointNotFoundException)
            {
                MessageBox.Show("The endpoint is not responding.  Please try again later...", "Service Exception", MessageBoxButton.OK, MessageBoxImage.Warning);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Service Exception", MessageBoxButton.OK, MessageBoxImage.Warning);
            }
            finally
            {
                if (_stopwatch.IsRunning)
                {
                    endTimer();
                    lblProcessing.Content = _processingHistory;
                }
            }
        }

        #endregion

        #region Private WS EXAMPLES

        /// <summary>
        /// Use this sample of code to call the UserInfoGetAll web service
        /// </summary>
        private void userInfoGetAll()
        {
            using (var client = new STWS_V2.ServiceRouterClient())
            {
                STWS_V2.GetUserDetailIn input = new STWS_V2.GetUserDetailIn()
                {
                    AuthToken = Properties.Settings.Default["WSToken"].ToString(),
                    EffectiveDate = DateTime.Now,
                    DataAction = new STWS_V2.DataAction()
                    {
                        Name = "SELECT-ALL"
                    }
                };
                STWS_V2.GetUserDetailRequest request = new STWS_V2.GetUserDetailRequest(input);
                STWS_V2.GetUserDetailResponse response = client.GetUserDetail(request);
                loadDataGrid_V2(response.GetUserDetailResult.Results);
            }
        }


        /// <summary>
        /// Use this sample of code to call the UserInfoGetByEmployeeID web service
        /// </summary>
        private void userInfoGetByEmployeeID()
        {
            using (var client = new STWS_V2.ServiceRouterClient())
            {
                STWS_V2.GetUserDetailIn input = new STWS_V2.GetUserDetailIn()
                {
                    AuthToken = Properties.Settings.Default["WSToken"].ToString(),
                    EffectiveDate = DateTime.Now,
                    DataAction = new STWS_V2.DataAction()
                    {
                        Name = "SELECT-EMPID",
                        Values = new List<string>() { txtSearchData.Text }
                    }
                };
                STWS_V2.GetUserDetailRequest request = new STWS_V2.GetUserDetailRequest(input);
                STWS_V2.GetUserDetailResponse response = client.GetUserDetail(request);
                loadDataGrid_V2(response.GetUserDetailResult.Results);
            }
        }

        /// <summary>
        /// Use this sample of code to call the UserInfoGetByDate web service
        /// </summary>
        private void userInfoGetByLName()
        {
            using (var client = new STWS_V2.ServiceRouterClient())
            {
                STWS_V2.GetUserDetailIn input = new STWS_V2.GetUserDetailIn()
                {
                    AuthToken = Properties.Settings.Default["WSToken"].ToString(),
                    EffectiveDate = DateTime.Now,
                    DataAction = new STWS_V2.DataAction()
                    {
                        Name = "SELECT-LNAME",
                        Values = new List<string>() { txtSearchData.Text}
                    }
                };
                STWS_V2.GetUserDetailRequest request = new STWS_V2.GetUserDetailRequest(input);
                STWS_V2.GetUserDetailResponse response = client.GetUserDetail(request);
                loadDataGrid_V2(response.GetUserDetailResult.Results);
            }
        }

        /// <summary>
        /// Use this sample of code to call the UserInfoDelete web service
        /// </summary>
        private bool userInfoDelete(string empID)
        {
            try
            {
                using (var client = new STWS.ServiceRouterClient())
                {
                    STWS.UserInfoDeleteByEmpIDRequest request = new STWS.UserInfoDeleteByEmpIDRequest();
                    request.param = new STWS.UserInfoGetParamsIn();
                    request.param.AuthToken = Properties.Settings.Default["WSToken"].ToString();
                    request.param.EmpIdentifier = empID;
                    STWS.UserInfoDeleteByEmpIDResponse response = client.UserInfoDeleteByEmpID(request);
                    return response.UserInfoDeleteByEmpIDResult;
                }

            }
            catch (FaultException<STWS.ServiceException> fe)
            {
                MessageBox.Show(fe.Detail.Message, "Service Exception", MessageBoxButton.OK, MessageBoxImage.Warning);
                return false;
            }
            catch (EndpointNotFoundException)
            {
                MessageBox.Show("The endpoint is not responding.  Please try again later...", "Service Exception", MessageBoxButton.OK, MessageBoxImage.Warning);
                return false;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Service Exception", MessageBoxButton.OK, MessageBoxImage.Warning);
                return false;
            }
        }

        #endregion

        #region Private Event Methods

        private void btnGetEmployees_Click(object sender, RoutedEventArgs e)
        {
            routeServiceCall(true);
        }

        private void btnSearch_Click(object sender, RoutedEventArgs e)
        {
            routeServiceCall();
        }

        private void btnAdd_Click(object sender, RoutedEventArgs e)
        {
            UserInfoAdd userAdd = new UserInfoAdd();
            userAdd.ShowDialog();
            userAdd.ShowInTaskbar = false;
        }

        private void btnDelete_Click(object sender, RoutedEventArgs e)
        {
            if (dataGrid1.SelectedItem != null)
            {
                STWS_V2.UserProfile user = (STWS_V2.UserProfile)dataGrid1.SelectedItem;
                string msg = String.Format("Are you sure you want to Delete EmployeeID '{0}'", user.EmpIdentifier);
                if (MessageBox.Show(msg, "Delete User", MessageBoxButton.OKCancel, MessageBoxImage.Question) == MessageBoxResult.OK)
                {
                    if (!userInfoDelete(user.EmpIdentifier))
                    {
                        MessageBox.Show("Unable to delete user, validate the web service has the correct permissions", "Delete User", MessageBoxButton.OKCancel, MessageBoxImage.Error);
                    }
                    else
                    {
                        userInfoGetAll();
                    }
                }
            }
            else
            {
                MessageBox.Show("Please select a user to Delete.", "Delete User", MessageBoxButton.OKCancel, MessageBoxImage.Information);
            }
        }

        #endregion


    }
}
