using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
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 SocketStudy.ClientApp
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        private TcpClient _tcpClient;

        public MainWindow()
        {
            InitializeComponent();
        }


        /// <summary>
        /// 连接服务网络
        /// </summary>
        private void btn_Connect_Click(object sender, RoutedEventArgs e)
        {
            if (_tcpClient?.Connected ?? false)
            {
                WriteLog("已经连接上!");
                return;
            }

            IPAddress serverAddress;
            if (!IPAddress.TryParse(textBox_ServerAddress.Text.Trim(), out serverAddress))
            {
                WriteLog("服务地址错误");
                return;
            }

            int serverPort = 6605;
            if (!int.TryParse(textBox_ServerPort.Text.Trim(), out serverPort))
            {
                WriteLog("服务器端口号错误");
                return;
            }
            else
            {
                if (serverPort <= 1024 || serverPort >= 65535)
                {
                    WriteLog("服务器端口号错误:必须在 1205-65534");
                    return;
                }
            }
            IPEndPoint serverEndPoint = new IPEndPoint(serverAddress, serverPort);

            IPAddress clientAddress;
            if (!IPAddress.TryParse(textBox_ClientAddress.Text.Trim(), out clientAddress))
            {
                WriteLog("本地连接地址错误");
                return;
            }
            int clientPort = 6901;
            if (!int.TryParse(textBox_ClientPort.Text.Trim(), out clientPort))
            {
                WriteLog("本地连接端口号错误");
                return;
            }
            else
            {
                if (clientPort <= 1024 || clientPort >= 65535)
                {
                    WriteLog("本地连接端口号错误:必须在 1205-65534");
                    return;
                }
            }
            IPEndPoint clientEndPoint = new IPEndPoint(clientAddress, clientPort);

            if (_tcpClient != null)
            {
                _tcpClient?.Dispose();
                _tcpClient = null;
            }

            try
            {
                _tcpClient = new TcpClient(clientEndPoint);
                _tcpClient.LingerState = new LingerOption(true, 0);
                //_tcpClient.SendTimeout = 10000;
                //_tcpClient.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
                _tcpClient.Connect(serverEndPoint);

                textBox_ServerAddress.IsEnabled = false;
                textBox_ServerPort.IsEnabled = false;
                textBox_ClientPort.IsEnabled = false;

                WriteLog("连接到服务器,成功");

                //接收服务端发来的数据
                ThreadPool.QueueUserWorkItem(obj =>
                {
                    try
                    {
                        do
                        {
                            NetworkStream streamToClient = _tcpClient.GetStream();
                            if (streamToClient.CanRead && streamToClient.DataAvailable)
                            {
                                byte[] buffer = new byte[8096];
                                var readCount = streamToClient.Read(buffer, 0, buffer.Length);
                                if (readCount <= 0)
                                {
                                    break;
                                }
                                var message = Encoding.UTF8.GetString(buffer, 0, readCount);

                                WriteLog($"接收到数据:{message}");

                            }
                            else
                            {
                                //WriteLog($"接收到无用数据包");
                            }
                        }
                        while (_tcpClient.Connected);
                    }
                    catch (Exception ex)
                    {

                    }
                    finally
                    { 
                    
                    }
                   
                });

                WriteLog($"连接操作执行完成,数据接收线程已启动!");
            }
            catch (SocketException socketException)
            {
                WriteLog($"连接到服务器时,异常:{socketException.Message}");
            }
            catch (Exception ex)
            {
                WriteLog($"连接到服务器时,异常:{ex.Message}");
            }
            finally
            {
                
            }
        }

        /// <summary>
        /// 关闭网络连接
        /// </summary>
        private void btn_Close_Click(object sender, RoutedEventArgs e)
        {
            if (_tcpClient == null || _tcpClient.Connected == false)
            {
                WriteLog("网络未连接到服务器,无需关闭!");
                return;
            }

            _tcpClient.GetStream().Close();
            //_tcpClient.GetStream().Dispose();
            _tcpClient.Close();
            
            _tcpClient.Client?.Disconnect(false);
            
            _tcpClient.Dispose();
            
            

            textBox_ServerAddress.IsEnabled = true;
            textBox_ServerPort.IsEnabled = true;
            textBox_ClientPort.IsEnabled = true;

            WriteLog($"连接已成功关闭!");
        }

        /// <summary>
        /// 使用连接,发送数据给服务器
        /// </summary>
        private void btn_Send_Click(object sender, RoutedEventArgs e)
        {
            if (_tcpClient == null)
            {
                WriteLog("网络连接不存在,请先连接到网络服务器!");
                return;
            }

            if (!_tcpClient.Connected)
            {
                WriteLog("请先连接到网络服务器!");
                return;
            }

            try
            {
                var message = textBox_SendData.Text.Trim();
                byte[] buffer = Encoding.UTF8.GetBytes(message);
                NetworkStream networkStream = _tcpClient.GetStream(); 
                networkStream.Write(buffer, 0, buffer.Length);
                WriteLog($"数据发送成功:{message}");
            }
            catch (Exception ex)
            {
                Console.WriteLine($"{ex.Message}");
                WriteLog($"{ex.Message}");
            }
            finally
            {

            }
        }

        /// <summary>
        /// 释放连接
        /// </summary>

        private void btn_Dispose_Click(object sender, RoutedEventArgs e)
        {
            if (_tcpClient == null)
            {
                WriteLog("网络未连接到服务器,无需释放!");
                return;
            }

            if (_tcpClient.Connected)
            {
                //_tcpClient.GetStream().Close();
                _tcpClient.Client?.Disconnect(true);
                _tcpClient.Close();
                WriteLog("关闭连接成功!");
            }

            
            _tcpClient.Dispose();
            

            textBox_ServerAddress.IsEnabled = true;
            textBox_ServerPort.IsEnabled = true;
            textBox_ClientPort.IsEnabled = true;

            WriteLog("连接已成功释放!");
        }

        /// <summary>
        /// 写日志信息
        /// </summary>
        private void WriteLog(string message)
        {
            Dispatcher.BeginInvoke(new Action(() =>
            {
                richTextBox_Log.AppendText($"{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")} {message}{System.Environment.NewLine}");
                richTextBox_Log.ScrollToEnd();
                Console.WriteLine(message);
            }));
        }
    }
}