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

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

        private TcpClient client;
        private NetworkStream netStream;
        public FrMain m;
        private bool control = false;

        #endregion

        #region 私有方法

        /// <summary>
        /// 信息发送函数
        /// </summary>
        /// <param name="n"></param>
        public void getin1(string n)
        {
            netStream = client.GetStream();
            string send = n + "\r\n";
            byte[] messsageByte = System.Text.Encoding.BigEndianUnicode.GetBytes(send.ToCharArray());
            netStream.Write(messsageByte, 0, messsageByte.Length);
            netStream.Flush();
        }

        /// <summary>
        /// 接收与解析函数，客户端核心，原理与服务器端同
        /// </summary>
        private void receive()
        {
            while (!control)
            {

                netStream = client.GetStream();
                byte[] messsageByte = new Byte[64];
                netStream.Read(messsageByte, 0, messsageByte.Length);
                string readNessage = System.Text.Encoding.BigEndianUnicode.GetString(messsageByte);
                string d;

                //截取前4个字符判断当前字符串类型
                d = readNessage.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 = readNessage.Substring(4, 8);
                    else m.lbPlay1.Text = readNessage.Substring(4, 8); ;
                }
                else
                    if (d == "xia1")
                    {
                        m.huihe++;
                        m.lbFristName.Text = "黑棋";
                    }
                    else
                        if (d == "xia0")
                        {
                            m.huihe++;
                            m.lbFristName.Text = "白棋";
                        }
                        else
                            if (d == "gin;")
                            {
                                if (readNessage.Substring(4, 3) == "hem")
                                    m.begin = true;
                                if (readNessage.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;")
                                {
                                    //坐标第一位<=9时，如（4，12）
                                    //此时接收为“hei;4，12”
                                    if (readNessage.Substring(5, 1) == ",")
                                    {
                                        m.wpx = Int32.Parse(readNessage.Substring(4, 1));
                                        if (readNessage.Substring(7, 1) == ",")
                                            m.wpy = Int32.Parse(readNessage.Substring(6, 1));
                                        //坐标两位均<=9时
                                        else
                                            m.wpy = Int32.Parse(readNessage.Substring(6, 2));
                                        //坐标前一位<=9，后一位>=10时
                                    }
                                    else
                                    {
                                        //坐标第一位>=10时
                                        m.wpx = Int32.Parse(readNessage.Substring(4, 2));
                                        if (readNessage.Substring(8, 1) == ",")
                                            m.wpy = Int32.Parse(readNessage.Substring(7, 1));
                                        //坐标前一位>=10，后一位<=9时
                                        else
                                            m.wpy = Int32.Parse(readNessage.Substring(7, 2));
                                        //坐标两位均>=10时
                                    }
                                    m.per = 1;
                                    tbChat.Text = "";
                                    m.player1 = true;
                                    m.tbRecord.Text = m.tbRecord.Text + "黑棋:" + "X" + m.wpx + "Y" + m.wpy + "\t";
                                    m.lbPState1.Text = "X" + m.wpx + "Y" + m.wpy;
                                    m.player2 = false;
                                    m.lbWait.Text = "等待白棋";
                                    if (m.lbFristName.Text == "黑棋")
                                        m.huihe++;
                                    m.begin = true;
                                    m.paintdown();
                                    //主窗体界面更新 
                                }
                                else
                                    if (d == "bai;")
                                    {
                                        //坐标第一位<=9时
                                        if (readNessage.Substring(5, 1) == ",")
                                        {
                                            m.wpx = Int32.Parse(readNessage.Substring(4, 1));
                                            if (readNessage.Substring(7, 1) == ",")
                                                m.wpy = Int32.Parse(readNessage.Substring(6, 1));
                                            //坐标两位均<=9时
                                            else
                                                m.wpy = Int32.Parse(readNessage.Substring(6, 2));
                                            //坐标前一位<=9，后一位>=10时
                                        }
                                        else
                                        {
                                            //坐标第一位>=10时
                                            m.wpx = Int32.Parse(readNessage.Substring(4, 2));
                                            if (readNessage.Substring(8, 1) == ",")
                                                //坐标前一位>=10，后一位<=9时
                                                m.wpy = Int32.Parse(readNessage.Substring(7, 1));
                                            else
                                                //坐标两位均>=10时 
                                                m.wpy = Int32.Parse(readNessage.Substring(7, 2));
                                        }
                                        m.per = 0;
                                        m.tbRecord.Text = m.tbRecord.Text + "白棋:" + "X" + m.wpx + "Y" + m.wpy + "\t";
                                        m.lbPState2.Text = "X" + m.wpx + "Y" + m.wpy;
                                        tbChat.Text = "";
                                        if (m.lbFristName.Text == "白棋")
                                            m.huihe++;
                                        m.player1 = false;
                                        m.player2 = true;
                                        m.lbWait.Text = "等待黑棋";
                                        m.begin = true;
                                        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(readNessage + "\r\n");
                m.paintdown();
                m.per = 2;
                // 恢复主窗体per值，准备下次接收
            }
        }

        #endregion

        public FrClient(FrMain k)
        {
            m = k;
            InitializeComponent();
        }

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

        //请求连接按纽
        private void btnAskCon_Click(object sender, EventArgs e)
        {
            try
            {
                int port = Int32.Parse(tbAskPort.Text);
                client = new TcpClient();
                client.Connect(tbIP.Text, port);
                lbSate.Text = "正常连接";
                //显示连接信息
                m.contet = true;
                m.lbPlay2.Text = tbCName.Text;
                //显示玩家姓名
                getin1("wja;" + tbCName.Text);
                //发送玩家姓名信息
                Thread thread1 = new Thread(new ThreadStart(receive));
                thread1.Start();


            }
            catch { MessageBox.Show("无法进行连接！"); }
        }

        //断开连接
        private void btnStopCon_Click(object sender, EventArgs e)
        {
            try
            {
                client.Close();
                m.contet = false;
                lbSate.Text = "已经断开连接！";

            }
            catch { MessageBox.Show("连接尚未建立，段开无效！"); }
        }
    }
}