using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using MES_SPC;
namespace ChatClient
{
    public static class webChatClient
    {
        private static bool stopFlag;
        /// <summary>
        /// 服务器是否反馈
        /// </summary>
        public static bool ServersResponse = false;
        /// <summary>
        /// 命令状态
        /// </summary>
        public static bool commandstatus = false;
        /// <summary>
        /// 是否正忙
        /// </summary>
        public static bool isworking = false;
        //与服务器的连接
        static TcpClient tcpClient= new TcpClient();
        //与服务器数据交互的流通道
        private static NetworkStream Stream;

        ////客户端的状态
        //private static string CLOSED = "closed";
        //private static string CONNECTED = "connected";
        //private static string state = CLOSED;
        ////private static bool stopFlag;

        static bool connect()
        {

            string HostName = ApplicationConfiguration.GPRSDataHost; ;
            //IPHostEntry dnstoip = new IPHostEntry();
            //dnstoip = Dns.GetHostEntry(HostName);
            //string HostIP = dnstoip.AddressList[0].ToString();
            string Port = ApplicationConfiguration.GPRSDataPort;
            return connect(HostName, Port);
        }
        private static bool connect(string HostName, string Port)
        {
            try
            {
                if (!tcpClient.Connected)
                {
                    tcpClient = new TcpClient();
                    tcpClient = TcpClientConnector.Connect(HostName, Int32.Parse(Port), 1000);
                    Stream = tcpClient.GetStream();
                    //Thread thread = new Thread(new ThreadStart(ServerResponse));
                    //thread.Start();
                    string cmd = "CONN|" + "WEB" + "|!";
                    Byte[] outbytes = System.Text.Encoding.Default.GetBytes(
                        cmd.ToCharArray());
                    Stream.Write(outbytes, 0, outbytes.Length);
                }
                return true;
            }
            catch (Exception ex)
            {
                return false;
            }

        }


        //当单击“离开”按钮时，便进入了btnExit_Click 处理程序。
        //在btnExit_Click 处理程序中，
        //将“EXIT”命令发送给服务器，此命令格式要与服务器端的命令格式一致
        private static void EXIT()
        {

            try
            {
                if (tcpClient.Connected)
                {
                    string message = "EXIT|" + "WEB" + "|!";
                    //将字符串转化为字符数组
                    Byte[] outbytes = System.Text.Encoding.Default.GetBytes(
                        message.ToCharArray());
                    Stream.Write(outbytes, 0, outbytes.Length);
                    tcpClient.Close();
                }
            }

            catch { }
        }

        private static void ServerResponse()
        {
            //定义一个byte数组，用于接收从服务器端发送来的数据，
            //每次所能接收的数据包的最大长度为1024个字节
            byte[] buff = new byte[1024];
            string msg;
            int len;
            try
            {
                if (!Stream.CanRead)
                {
                    //return "不可读";
                    return;
                }
                stopFlag = false;
                while (!stopFlag)
                {
                    //从流中得到数据，并存入到buff字符数组中
                    len = Stream.Read(buff, 0, buff.Length);
                    if (len < 1)
                    {
                        Thread.Sleep(200);
                        continue;
                    }
                    ServersResponse = true;
                }
                tcpClient.Close();
                //关闭连接
            }
            catch
            {
                //return "网络发生错误";
            }
        }
        static string command = "";
        //当点击“发送”按钮时，便会进入btnSend_Click处理程序。
        //在btnSend_Click处理程序中，如果不是私聊，
        //将“CHAT”命令发送给服务器，
        //否则（为私聊），将“PRIV”命令发送给服务器，
        //注意命令格式一定要与服务器端的命令格式一致
        public static void sentmessage(string GPRScommand)
        {
            if (isworking)
            {
                return;
            }
            isworking = true;
            try
            {
                command = GPRScommand;
                commandstatus = false;
                if (connect())
                {
                    byte[] outbytes = System.Text.Encoding.ASCII.GetBytes(command.ToCharArray());
                    Stream.Write(outbytes, 0, outbytes.Length);
                    commandstatus = true;
                }
                else 
                {
                    commandstatus = false;
                }
            }
            catch (Exception err)
            {
                tcpClient.Close();
                commandstatus = false;
            }
            isworking = false;
        }



    }
}
