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.Collections.ObjectModel;
using System.ComponentModel;
using TouchSocket.Core;
using TouchSocket.Sockets;
using System.Threading;
using System.Configuration;

namespace Tcp.Test2
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window, INotifyPropertyChanged
    {
        private ObservableCollection<MessageModel> _listMessages;
        private ICommand _sendCommand;
        private String _currentInput;
        private String _statusMessage;
        private TcpClient _tcpClient;
        private Encoding _encoding;
        private TouchSocketConfig _tcpClientConfig;
        private static readonly String _serverIP, _serverPort;
        public MainWindow()
        {
            InitializeComponent();
            this.DataContext = this;
            this.Loaded += MainWindow_Loaded;
        }
        static MainWindow() 
        {
            _serverIP = ConfigurationManager.AppSettings["ServerIp"];
            if (String.IsNullOrWhiteSpace(_serverIP)) 
            {
                _serverIP = "127.0.0.1";
            }
            _serverPort = ConfigurationManager.AppSettings["ServerPort"];
            if (String.IsNullOrWhiteSpace(_serverPort))
            {
                _serverPort = "8308";
            }
        }

        public event PropertyChangedEventHandler? PropertyChanged;

        public ObservableCollection<MessageModel> ListMessage 
        {
            get { return _listMessages; }
            set 
            {
                _listMessages = value;
                OnPropertyChanged(nameof(ListMessage));
            }
        }
        public ICommand SendCommand 
        {
            get { return _sendCommand; }
            set 
            {
                _sendCommand = value;
                OnPropertyChanged(nameof(SendCommand));
            }
        }
        public String CurrentInput 
        { 
            get { return _currentInput; } 
            set 
            {
                _currentInput = value; 
                OnPropertyChanged(nameof(CurrentInput)); 
            }
        }
        public String StatusMessage 
        {
            get { return _statusMessage; }
            set 
            {
                _statusMessage = value;
                OnPropertyChanged(nameof(StatusMessage));
            }
        }
        private void MainWindow_Loaded(object sender, RoutedEventArgs e)
        {
            this.SendCommand = new DelegateCommand(this.SendCommandHandler);
            this.ListMessage = new ObservableCollection<MessageModel>();
            Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
            _encoding = Encoding.GetEncoding("gb2312");
            //声明配置
            _tcpClientConfig = new TouchSocketConfig();
            _tcpClientConfig.SetRemoteIPHost(new IPHost($"{_serverIP}:{_serverPort}"))
            //config.SetRemoteIPHost(new IPHost("192.168.2.253:8308"))
                .UsePlugin()
                .ConfigurePlugins(a =>
                {
                    a.UseReconnection(5, true, 1000);
                })
                .SetBufferLength(1024 * 10);
            _tcpClient = CreateClient();
            //载入配置
            Task.Run(() =>
            {
                ConnectServer();
            });
        }
        private void OnPropertyChanged(String propertyName) 
        {
            if (PropertyChanged != null) 
            {
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
            }
        }
        private TouchSocket.Sockets.TcpClient CreateClient() 
        {
            if (_tcpClient != null)
            {
                _tcpClient.Dispose();
            }
            _tcpClient = new TouchSocket.Sockets.TcpClient();
            _tcpClient.Setup(_tcpClientConfig);
            _tcpClient.Connected += (client, e) =>
            {
                Application.Current.Dispatcher.Invoke(() =>
                {
                    this.StatusMessage = "成功连接服务器";
                });
            };//成功连接到服务器
            _tcpClient.Disconnected += (client, e) =>
            {
                Application.Current.Dispatcher.Invoke(() =>
                {
                    this.StatusMessage = "与服务器断开连接";
                });
                _tcpClient = CreateClient();
            };//从服务器断开连接，当连接不成功时不会触发。
            _tcpClient.Received += (client, byteBlock, requestInfo) =>
            {
                //从服务器收到信息
                string mes = _encoding.GetString(byteBlock.Buffer, 0, byteBlock.Len);
                Application.Current.Dispatcher.Invoke(() =>
                {
                    ListMessage.Add(new MessageModel
                    {
                        IsAck = true,
                        Message = mes
                    });
                });
            };
            return _tcpClient;
        }
        private void ConnectServer()
        {
            while (true)
            {
                if (_tcpClient != null) 
                {
                    if (!_tcpClient.Online)
                    {
                        Console.WriteLine("正在连接服务器...");
                        try
                        {
                            _tcpClient.Connect();
                            Console.WriteLine("连接成功");
                        }
                        catch (Exception ex)
                        {
                            Console.WriteLine("连接失败：" + ex.Message);
                            Thread.Sleep(1000);
                        }
                    }
                }
                Thread.Sleep(1000);
            }
        }
        private void SendCommandHandler() 
        {
            if (!String.IsNullOrWhiteSpace(this._currentInput))
            {
                try
                {
                    _tcpClient.Send(_encoding.GetBytes(this._currentInput));
                    this.StatusMessage = String.Empty;
                    ListMessage.Add(new MessageModel()
                    {
                        Message = this._currentInput
                    });
                }
                catch (Exception ex)
                {
                    this.StatusMessage = "发送失败：" + ex.Message;
                }
            }
        }
    }
}
