using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;
using System.Threading;

namespace GoBang
{
    public partial class FrServer : Form
    {
        #region 变量

        private NetworkStream netStream;
        public Socket mySock;
        private TcpListener listener;
        public FrMain m;

        /// <summary>
        /// 获取本地IP
        /// </summary>
        IPAddress ip = Dns.GetHostAddresses(Dns.GetHostName())[0];

        #endregion

        #region 私有方法

        /// <summary>
        ///发送信息并在当前界面显示 
        /// </summary>
        private void recieve()
        {
            while (true)
            {
                mySock = listener.AcceptSocket();
                if (mySock.Connected)
                {
                    m.contet = true;
                    lbServerState.Text = "已经与客户建立连接。";
                    //当前状态显示
                    m.lbPlay1.Text = tbSName.Text;
                    //显示黑棋玩家姓名
                    getin("wja;" + tbSName.Text);
                    //发送玩家姓名字符串
                    Thread thread = new Thread(new ThreadStart(round));
                    thread.Start();
                }
            }
        }

        /// <summary>
        /// 信息发送函数
        /// </summary>
        /// <param name="n"></param>
        public void getin(string n)
        {
            try
            {
                netStream = new NetworkStream(mySock);
                string send = n + "\r\n";
                byte[] messageByte = System.Text.Encoding.BigEndianUnicode.GetBytes(send.ToCharArray());
                netStream.Write(messageByte, 0, messageByte.Length);
                netStream.Flush();
            }
            catch { MessageBox.Show("发送无效！连接不正常!"); }
        }

        /// <summary>
        /// 信息接收与解析函数，服务器核心
        /// </summary>
        private void round()
        {
            while (true)
            {
                byte[] messageByte = new Byte[64];
                netStream = new NetworkStream(mySock);
                netStream.Read(messageByte, 0, messageByte.Length);
                string readMessage = System.Text.Encoding.BigEndianUnicode.GetString(messageByte);
                string d;
                //截取前4个字符判断当前字符串类型
                d = readMessage.Substring(0, 4);

                //d=="wja;" 表示接收为玩家姓名，取后4字符
                //d=="xia1" 表示黑棋先手
                //d=="xia0" 表示白棋先手
                //d=="gin;" 接收重新开始信息
                //d=="hei;" 接收黑棋下子信息
                //d=="bai;" 接收白棋下子信息
                //d=="in0;" 表示白棋获胜，显示获胜玩家姓名
                //d=="in1;" 表示黑棋获胜，显示获胜玩家姓名
                //d=="now;" 表示平局
                //除上述情况默认为聊天信息，在主窗体中显示


                if (d == "wja;")
                {
                    if (m.hem) m.lbPlay2.Text = readMessage.Substring(4, 8);
                    else m.lbPlay1.Text = readMessage.Substring(4, 8);
                    getin("wja;" + tbSName.Text);
                }
                else
                    if (d == "xia1")
                    {
                        m.lbFristName.Text = "黑棋";
                        m.huihe++;
                    }
                    else
                        if (d == "xia0")
                        {
                            m.lbFristName.Text = "白棋";
                            m.huihe++;
                        }
                        else
                            if (d == "gin;")
                            {

                                if (readMessage.Substring(4, 3) == "hem")
                                    m.begin = true;
                                if (readMessage.Substring(4, 3) == "pat")
                                    m.begin = false;
                                m.nplayers = false;
                                m.wplayers = true;
                                m.huihe = 0;
                                m.lbFristName.Text = "待定";
                                m.lbWinner.Text = "待定";
                                m.gamebegin();
                                m.lbPState1.Text = "待定";
                                m.lbPState2.Text = "待定";
                                m.lbCountNum.Text = "" + m.huihe;
                                m.lbWait.Text = "先手未定";
                                m.tbRecord.Text = "";

                            }
                            else
                                if (d == "hei;")
                                {
                                    if (readMessage.Substring(5, 1) == ",")
                                    {
                                        //坐标第一位<=9时，如（4，12）
                                        //此时接收为“hei;4，12”
                                        m.wpx = Int32.Parse(readMessage.Substring(4, 1));
                                        if (readMessage.Substring(7, 1) == ",")
                                            //坐标两位均<=9时
                                            m.wpy = Int32.Parse(readMessage.Substring(6, 1));
                                        else
                                            //坐标前一位<=9，后一位>=10时
                                            m.wpy = Int32.Parse(readMessage.Substring(6, 2));
                                    }
                                    else
                                    {
                                        //坐标第一位>=10时
                                        m.wpx = Int32.Parse(readMessage.Substring(4, 2));
                                        if (readMessage.Substring(8, 1) == ",")
                                            //坐标前一位>=10，后一位<=9时
                                            m.wpy = Int32.Parse(readMessage.Substring(7, 1));
                                        else
                                            //坐标两位均>=10时
                                            m.wpy = Int32.Parse(readMessage.Substring(7, 2));
                                    }
                                    m.per = 1;
                                    m.tbRecord.Text = m.tbRecord.Text + "黑棋:" + "X" + m.wpx + "Y" + m.wpy + "\t";
                                    m.lbPState1.Text = "X" + m.wpx + "Y" + m.wpy;
                                    tbChat.Text = "";
                                    m.player1 = true;
                                    m.player2 = false;
                                    m.lbWait.Text = "等待白棋";
                                    if (m.lbFristName.Text == "黑棋")
                                        m.huihe++;
                                    m.paintdown();
                                    m.begin = true;
                                    //主窗体界面更新               

                                }
                                else
                                    if (d == "bai;")
                                    {
                                        if (readMessage.Substring(5, 1) == ",")
                                        {
                                            //坐标第一位<=9时
                                            m.wpx = Int32.Parse(readMessage.Substring(4, 1));
                                            if (readMessage.Substring(7, 1) == ",")
                                                //坐标两位均<=9时
                                                m.wpy = Int32.Parse(readMessage.Substring(6, 1));
                                            else
                                                //坐标前一位<=9，后一位>=10时
                                                m.wpy = Int32.Parse(readMessage.Substring(6, 2));
                                        }
                                        else
                                        {
                                            //坐标第一位>=10时
                                            m.wpx = Int32.Parse(readMessage.Substring(4, 2));
                                            if (readMessage.Substring(8, 1) == ",")
                                                //坐标前一位>=10，后一位<=9时
                                                m.wpy = Int32.Parse(readMessage.Substring(7, 1));
                                            else
                                                //坐标两位均>=10时
                                                m.wpy = Int32.Parse(readMessage.Substring(7, 2));
                                        }
                                        m.tbRecord.Text = m.tbRecord.Text + "白棋:" + "X" + m.wpx + "Y" + m.wpy + "\t";
                                        m.lbPState2.Text = "X" + m.wpx + "Y" + m.wpy;
                                        m.per = 0;
                                        tbChat.Text = "";
                                        m.player2 = true;
                                        m.player1 = false;
                                        m.lbWait.Text = "等待黑棋";
                                        m.begin = true;
                                        if (m.lbFristName.Text == "白棋")
                                            m.huihe++;
                                        m.paintdown();

                                        //主窗体界面更新 
                                    }
                                    else
                                        if (d == "in0;")
                                        {
                                            m.win0 = true;
                                            m.lbWinner.Text = m.lbPlay2.Text;
                                            m.paintdown();
                                        }
                                        else
                                            if (d == "in1;")
                                            {
                                                m.win1 = true;
                                                m.lbWinner.Text = m.lbPlay1.Text;
                                                m.paintdown();
                                            }
                                            else
                                                if (d == "now;")
                                                {
                                                    m.nowin = true;
                                                    m.lbWinner.Text = "无";
                                                    m.paintdown();
                                                }
                                                else
                                                    m.tbChat.AppendText(readMessage + "\r\n");
                m.paintdown();
                m.per = 2;
                // 恢复主窗体per值，准备下次接收
            }
        }

        #endregion

        #region 窗体方法

        public FrServer(FrMain K)
        {
            m = K;
            InitializeComponent();
        }

        //开始监听按钮
        private void btnListenSta_Click(object sender, EventArgs e)
        {
            try
            {
                listener = new TcpListener(ip, Convert.ToInt32(tbPort.Text));
                listener.Start();
                lbServerState.Text = string.Format("正处于待机状态…………\t服务器IP：{0}\t 端口号：{1}", ip,  Convert.ToInt32(tbPort.Text));
                //当前状态显示
                Thread thread = new Thread(new ThreadStart(recieve));
                thread.Start();
            }
            catch (Exception ee) { MessageBox.Show(ee.Message); }
        }

        //信息发送按纽
        private void btnSend_Click(object sender, EventArgs e)
        {
            try
            {
                getin(tbSName.Text + " 说： " + tbChat.Text);
                //发送聊天信息
                m.tbChat.AppendText(tbSName.Text + " 说： " + tbChat.Text + "\t");
                //在主窗体中显示聊天信息
                tbChat.Text = "";
                //清空聊天信息栏
            }
            catch { MessageBox.Show("发送无效！  \n可能存在以下原因造成连接不正常！：\n1.连接多次\n2.已经关闭连接\n请关闭窗口重新连接。"); }
        }

        //停止监听按纽
        private void btnListenStop_Click(object sender, EventArgs e)
        {
            try
            {
                mySock.Close();
                listener.Stop();
                m.contet = false;
                //置主窗体中contet为false，连接断开
                lbServerState.Text = "已经停止监听！";
            }
            catch { MessageBox.Show("监听尚未开始，关闭无效！"); }
        }

        #endregion
    }
}