using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Net;
using System.Net.Sockets;
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.Windows.Threading;

namespace Cashier
{
    /// <summary>
    /// Interaction logic for MenuPage.xaml
    /// </summary>
    public partial class MenuPage : Page
    {
        ObservableCollection<RootDataOfProductInOrder> ProductInOrder = new ObservableCollection<RootDataOfProductInOrder>();

        public MenuPage()
        {
            InitializeComponent();
            List<string> TypeOfPayment = new List<string>();
            TypeOfPayment.Add("Наличные");
            TypeOfPayment.Add("Карта");
            CmbTypeOfPayment.ItemsSource = TypeOfPayment;
            TabCashier.SelectedIndex = 1;
            BtnPayment.IsEnabled = Helper.WorkShiftID is null ? false : true;
            ProductInStoreList.ItemsSource = Helper.ProductInStore;
            ProductInOrderList.ItemsSource = ProductInOrder;
            DispatcherTimer timer = new DispatcherTimer();
            timer.Interval = new TimeSpan(0, 0, 1);
            timer.Tick += Timer_Tick;
            timer.Start();
        }

        private void Timer_Tick(object sender, EventArgs e)
        {
            BtnPayment.IsEnabled = Helper.WorkShiftID is null ? false : true;
        }

        private void TxtSearch_TextChanged(object sender, TextChangedEventArgs e)
        {
            ProductInStoreList.ItemsSource = Helper.ProductInStore.Where(x => x.NameProduct.Contains(TxtSearch.Text)).ToList();
        }

        private void BtnDeleteInOrder_Click(object sender, RoutedEventArgs e)
        {
            var CurrentProduct = (sender as Button).DataContext as RootDataOfProductInOrder;
            ProductInOrder.Remove(CurrentProduct);
            TotalCost();
        }

        public void TotalCost()
        {
            decimal TotalCost = 0;
            foreach (var item in ProductInOrder)
            {
                TotalCost += item.ProductInStore.PriceOfOne * item.AmountProduct;
            }
            TxtTotalCost.Text = TotalCost.ToString("F2") + " руб.";
        }

        private void BtnAddInOrder_Click(object sender, RoutedEventArgs e)
        {
            if (string.IsNullOrEmpty(TxtProductCode.Text) || TxtProductCode.Text.All(char.IsDigit) == false)
            {
                Helper.ErrorMessage("Не корректный номер продукта");
                return;
            } 
            if (string.IsNullOrEmpty(TxtAmountProduct.Text) || TxtAmountProduct.Text.All(char.IsDigit) == false)
            {
                Helper.ErrorMessage("Не корректное количество");
                return;
            }
            var CurrentProduct = Helper.ProductInStore.FirstOrDefault(x => x.BarCode == TxtProductCode.Text);
            if (CurrentProduct == null)
            {
                Helper.ErrorMessage("Продукт не найден");
                return;
            }
            RootDataOfProductInOrder dataOfProductInOrder = new RootDataOfProductInOrder()
            {   
                ProductInStore = CurrentProduct,
                AmountProduct = Convert.ToInt32(TxtAmountProduct.Text) 
            };
            ProductInOrder.Add(dataOfProductInOrder);
            TotalCost();
        }

        public void Print()
        {
            PrintDialog printDialog = new PrintDialog();
            TextBlock DataOfOrder = new TextBlock();
            string Text = "";
        }

        public async void PostDataOfOrder()
        {
            RootDataOfOrder rootDataOfOrder = new RootDataOfOrder()
            {
                Date = DateTime.Now,
                IDWorkShift = Helper.WorkShiftID.Value,
                IDPaymentMetod = CmbTypeOfPayment.SelectedIndex + 1,
                ProductInOrders = ProductInOrder.ToList()
            };
            string Message = "Data of Order =" + JsonConvert.SerializeObject(rootDataOfOrder);
            string IDStore = Helper.IDStore.ToString();
            if (IDStore.Length == 1) IDStore = IDStore.Insert(0, "0");
            IPEndPoint iPEndPoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), Convert.ToInt32("102" + IDStore));
            Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            await socket.ConnectAsync(iPEndPoint);
            byte[] data = Encoding.UTF8.GetBytes(Message);
            socket.Send(data);
        }
        private void BtnCreateOrder_Click(object sender, RoutedEventArgs e)
        {
            if (ProductInOrder.Count == 0)
            {
                return;
            }
            PostDataOfOrder();
            ProductInOrder.Clear();
        }
    }
}
