using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
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.Configuration;
using System.Windows.Threading;
using cosicomodo.quantycaReference;
namespace cosifacile
{
    /// <summary>
    /// Logica di interazione per Orders.xaml
    /// </summary>
    public partial class Orders : Page
    {
        MainPage parentWindow;
        DispatcherTimer timer = new DispatcherTimer();
        static int cTimerSec;
        private bool helpOrNot = false;
        getOrdersOutputType pageOrders;
        bool toPick = false;

        public Orders()
        {
            InitializeComponent();
            UIElement parent = App.Current.MainWindow;
            parentWindow = (MainPage)parent;
            parent = null;

        }

        public Orders(getOrdersOutputType oDetails)
        {
            InitializeComponent();
            pageOrders = oDetails;
            UIElement parent = App.Current.MainWindow;
            parentWindow = (MainPage)parent;
            parent = null;
            List<string> countOrders = new List<string>();
            txtAddress.Text = parentWindow.rp.address;
            foreach (sezioniOrdineType current in oDetails.ordini)
            {
                if (current.testata.ordineBase.statoOrdine == "PRONTO_PER_IL_RITIRO")
                {
                    bool orderOK = isOrderOk(current);
                    helpOrNot = helpOrNot || !orderOK;
                    ordersElement ord = new ordersElement(current, orderOK);
                    ord.Name = "ord" + current.testata.ordineBase.idOrdineUtente;
                    ord.elementDetails.Name = "grd" + current.testata.ordineBase.idOrdineUtente;
                    ord.lblStato.Tag = current.testata.ordineBase.idOrdineUtente;
                    if (!orderOK)
                        ord.lblStato.MouseUp += lblStato_MouseUp;
                    ord.lblStato.Uid = current.testata.ordineBase.idOrdineUtente;
                    ord.elementDetails.Visibility = System.Windows.Visibility.Hidden;
                    ord.Height = 100;
                    //ord.grdElement.Visibility = System.Windows.Visibility.Hidden;
                    rpPanel.Children.Add(ord);
                    countOrders.Add(current.testata.ordineBase.idOrdineUtente);
                }
            }
            if (countOrders.Count == 1 && isOrderOk(oDetails.ordini[0]))
            {
                orderToDeliveryOutputType orderToDelivery = new orderToDeliveryOutputType();
                string[] orderIds = new string[1];
                orderIds[0] = countOrders[0];
                //statusType delStat = parentWindow.sl.orderToDelivery(orderIds, "", out orderToDelivery);
                statusType delStat = parentWindow.sl.orderToDelivery(orderIds, out orderToDelivery, parentWindow.rp.settings, false);
                if (delStat.codiceStato == 200)
                {
                    Parking sub = new Parking(orderToDelivery.idParcheggio);
                    parentWindow.Content = sub;
                }
                else
                {
                    NoService sub = new NoService();
                    parentWindow.Content = sub;
                }
            }
        }

        bool isOrderOk(sezioniOrdineType customerOrders)
        {
            bool retValue = true;
            foreach(articoloOrdineType current in customerOrders.dettaglio)
            {
                if (current.articoloBase.quantita == 0)
                    retValue = false;
                if (current.articoloSostituzioni.flagSostituito)
                    retValue = false;
            }
            retValue = false;
            return retValue;
        }

        void lblStato_MouseUp(object sender, MouseButtonEventArgs e)
        {
            try
            {
                TextBlock caller = (TextBlock)sender;
                string xname = "ord" + caller.Tag.ToString();
                foreach (UIElement current in rpPanel.Children)
                {
                    if (current.GetType() == typeof(ordersElement))
                    {
                        ordersElement ttx = (ordersElement)current;
                        if (ttx.Name == xname)
                        {
                            if (ttx.elementDetails.Visibility == System.Windows.Visibility.Hidden)
                            {
                                ttx.grdElement.RowDefinitions.Add(new RowDefinition());
                                ttx.grdElement.RowDefinitions[1].Height = new GridLength(900);
                                ttx.elementDetails.Visibility = System.Windows.Visibility.Visible;
                                ttx.Height = 900;
                            }
                            else
                            {
                                ttx.elementDetails.Visibility = System.Windows.Visibility.Hidden;
                                ttx.grdElement.RowDefinitions.RemoveAt(1);
                                ttx.Height = 100;
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {

            }
        }

        public static T FindChild<T>(DependencyObject parent, string childName)
           where T : DependencyObject
        {
            // Confirm parent and childName are valid. 
            if (parent == null) return null;

            T foundChild = null;

            int childrenCount = VisualTreeHelper.GetChildrenCount(parent);
            for (int i = 0; i < childrenCount; i++)
            {
                var child = VisualTreeHelper.GetChild(parent, i);
                // If the child is not of the request child type child
                T childType = child as T;
                if (childType == null)
                {
                    // recursively drill down the tree
                    foundChild = FindChild<T>(child, childName);

                    // If the child is found, break so we do not overwrite the found child. 
                    if (foundChild != null) break;
                }
                else if (!string.IsNullOrEmpty(childName))
                {
                    var frameworkElement = child as FrameworkElement;
                    // If the child's name is set for search
                    if (frameworkElement != null && frameworkElement.Name == childName)
                    {
                        // if the child's name is of the request name
                        foundChild = (T)child;
                        break;
                    }
                }
                else
                {
                    // child element found.
                    foundChild = (T)child;
                    break;
                }
            }

            return foundChild;
        }

        private void TimerTick(object sender, EventArgs e)
        {
            try
            {
                //parentWindow.logMsg("DatiScontrino - TimerTick");
                cTimerSec -= 1;
                if (cTimerSec <= 0)
                {
                    exitPage();
                }

                else
                    lblTimer.Content = cTimerSec.ToString();
            }

            catch { }
        }

        private void exitPage()
        {
            parentWindow.logMsg("Uscita pagina Orders");
            timer.Stop();
            CosiComodo SUB = new CosiComodo();
            parentWindow.Content = SUB;
            parentWindow = null;
            SUB = null;
        }

        private void lblBack_MouseUp(object sender, MouseButtonEventArgs e)
        {
            exitPage();
        }

        private void lblAnnulla_MouseUp(object sender, MouseButtonEventArgs e)
        {
            exitPage();
        }

        private void Page_Loaded(object sender, RoutedEventArgs e)
        {
            imgRP.Source = parentWindow.rp.signImg;

            imgRP.Width = parentWindow.rp.signWidth;
            cTimerSec = Convert.ToInt32(ConfigurationManager.AppSettings["timerRead"]);
            timer = new DispatcherTimer();
            timer.Interval = TimeSpan.FromSeconds(1);// TimeSpan.FromSeconds(Convert.ToInt32(ConfigurationManager.AppSettings["timerDaGiocaAHome"]));
            timer.Tick += TimerTick;
            timer.Start();

            /*
            foreach (sezioniOrdineType current in pageOrders.ordini)
            {
                if (current.testata.ordineBase.statoOrdine != "PRONTO_PER_IL_RITIRO")
                {
                    helpOrNot = true;
                }

            }
            */
        }

        private void grdRitira_MouseUp(object sender, MouseButtonEventArgs e)
        {
            grdRitira.MouseUp -= grdRitira_MouseUp;
            if (helpOrNot)
                grdAccept.Visibility = System.Windows.Visibility.Visible;
            else
            {
                try
                {
                    grdAccept.Visibility = System.Windows.Visibility.Hidden;
                    orderToDeliveryOutputType orderToDelivery = new orderToDeliveryOutputType();
                    string[] orderIds = new string[pageOrders.ordini.Length];
                    int i = 0;
                    foreach (sezioniOrdineType current in pageOrders.ordini)
                    {
                        orderIds[i] = current.testata.ordineBase.idOrdineUtente;
                        i++;
                    }

                    statusType delStat = parentWindow.sl.orderToDelivery(orderIds, out orderToDelivery, parentWindow.rp.settings, false);
                    if (delStat.codiceStato == 200)
                    {
                        Parking sub = new Parking(orderToDelivery.idParcheggio);
                        parentWindow.Content = sub;
                    }
                    else
                    {
                        NoService sub = new NoService();
                        parentWindow.Content = sub;
                    }
                }
                catch (Exception ex)
                {
                    NoService sub = new NoService();
                    parentWindow.Content = sub;
                }
            }
        }

        private void grdClose_MouseUp(object sender, MouseButtonEventArgs e)
        {
            grdNotFound.Visibility = System.Windows.Visibility.Hidden;
        }

        private void grdAnnulla_MouseUp(object sender, MouseButtonEventArgs e)
        {
            grdNotFound.Visibility = System.Windows.Visibility.Hidden;
        }

        private void grdConfirm_MouseUp(object sender, MouseButtonEventArgs e)
        {
            grdConfirm.MouseUp -= grdRitira_MouseUp;
            try
            {
                grdAccept.Visibility = System.Windows.Visibility.Hidden;
                orderToDeliveryOutputType orderToDelivery = new orderToDeliveryOutputType();
                string[] orderIds = new string[pageOrders.ordini.Length];
                int i = 0;
                foreach (sezioniOrdineType current in pageOrders.ordini)
                {
                    orderIds[i] = current.testata.ordineBase.idOrdineUtente;
                    i++;
                }

                statusType delStat = parentWindow.sl.orderToDelivery(orderIds, out orderToDelivery, parentWindow.rp.settings, false);
                if (delStat.codiceStato == 200)
                {
                    Parking sub = new Parking(orderToDelivery.idParcheggio);
                    parentWindow.Content = sub;
                }
                else
                {
                    NoService sub = new NoService();
                    parentWindow.Content = sub;
                }
            }
            catch(Exception ex)
            {
                NoService sub = new NoService();
                parentWindow.Content = sub;
            }
        }

        private void grdCloseAccept_MouseUp(object sender, MouseButtonEventArgs e)
        {
            grdAccept.Visibility = System.Windows.Visibility.Hidden;
        }

        private void grdPickHelp_MouseUp(object sender, MouseButtonEventArgs e)
        {
            grdAssistenza.MouseUp -= grdPickHelp_MouseUp;
            try
            {
                grdAccept.Visibility = System.Windows.Visibility.Hidden;
                orderToDeliveryOutputType orderToDelivery = new orderToDeliveryOutputType();
                string[] orderIds = new string[pageOrders.ordini.Length];
                int i = 0;
                foreach (sezioniOrdineType current in pageOrders.ordini)
                {
                    orderIds[i] = current.testata.ordineBase.idOrdineUtente;
                    i++;
                }

                statusType delStat = parentWindow.sl.orderToDelivery(orderIds, out orderToDelivery, parentWindow.rp.settings, true);
                if (delStat.codiceStato == 200)
                {
                    Parking sub = new Parking(orderToDelivery.idParcheggio);
                    parentWindow.Content = sub;
                }
                else
                {
                    NoService sub = new NoService();
                    parentWindow.Content = sub;
                }
            }
            catch (Exception ex)
            {
                NoService sub = new NoService();
                parentWindow.Content = sub;
            }
        }

        private void grdAccept_MouseUp(object sender, MouseButtonEventArgs e)
        {
            try
            {
                grdAccept.Visibility = System.Windows.Visibility.Hidden;
                orderToDeliveryOutputType orderToDelivery = new orderToDeliveryOutputType();
                string[] orderIds = new string[pageOrders.ordini.Length];
                int i = 0;
                foreach (sezioniOrdineType current in pageOrders.ordini)
                {
                    orderIds[i] = current.testata.ordineBase.idOrdineUtente;
                    i++;
                }

                statusType delStat = parentWindow.sl.orderToDelivery(orderIds, out orderToDelivery, parentWindow.rp.settings, false);
                if (delStat.codiceStato == 200)
                {
                    Parking sub = new Parking(orderToDelivery.idParcheggio);
                    parentWindow.Content = sub;
                }
                else
                {
                    NoService sub = new NoService();
                    parentWindow.Content = sub;
                }
            }
            catch(Exception ex)
            {
                NoService sub = new NoService();
                parentWindow.Content = sub;
            }
        }
    }
}
