using Newtonsoft.Json;
using System;
using System.Collections.Generic;
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;

namespace Cashier
{
    /// <summary>
    /// Interaction logic for StartWorkPage.xaml
    /// </summary>
    public partial class StartWorkPage : Page
    {
        public StartWorkPage()
        {
            InitializeComponent();
        }

        public async void ConnectToStore(string IDStore, string Message)
        {
            try
            {
                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);
                socket.Connect(iPEndPoint);
                byte[] data = Encoding.UTF8.GetBytes(Message);
                socket.Send(data);
                data = new byte[256];
                int byts = 0;
                StringBuilder builder = new StringBuilder();
                do
                {
                    byts = socket.Receive(data, data.Length, 0);
                    builder.Append(Encoding.UTF8.GetString(data, 0, byts));
                } while (socket.Available > 0);
                string response = builder.ToString();
                if (response.Contains("Добро пожаловать"))
                {
                    string Json = response.Split('=')[1];
                    Helper.ProductInStore = JsonConvert.DeserializeObject<List<RootDataOfProductInStore>>(Json);
                    Helper.InformationMessage(response.Split('=')[0]);
                    ManagerFrame.MainFrame.Navigate(new MenuPage());
                }
                else
                {
                    Helper.ErrorMessage(response);
                }
                socket.Shutdown(SocketShutdown.Both);
                socket.Close();
            }
            catch (Exception)
            {
                Helper.ErrorMessage("Нет ответа от сервера");
            }

        }

        private void BtnConnect_Click(object sender, RoutedEventArgs e)
        {
            if (string.IsNullOrEmpty(TxtIDStore.Text) || TxtIDStore.Text.All(char.IsDigit) == false)
            {
                Helper.ErrorMessage("Не корректный ID");
                return;
            }
            if (string.IsNullOrEmpty(TxtNumberCashier.Text) || TxtNumberCashier.Text.All(char.IsDigit)== false)
            {
                Helper.ErrorMessage("Не корректный номер кассы");
                return;
            }
            if (string.IsNullOrEmpty(TxtCodeEmployee.Text) || TxtCodeEmployee.Text.All(char.IsDigit) == false)
            {
                Helper.ErrorMessage("Не корректный код сотрудника");
                return;
            }
            Helper.IDStore = Convert.ToInt32(TxtIDStore.Text);
            Helper.IDCashier = Convert.ToInt32(TxtNumberCashier.Text);
            Helper.NumberEmployee = TxtCodeEmployee.Text;
            string Message = $"Authorization - Code cashier={TxtNumberCashier.Text}; Code employee ={TxtCodeEmployee.Text}";
            ConnectToStore(TxtIDStore.Text, Message);
        }
    }
}
