using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using InTheHand.Net;
using InTheHand.Net.Bluetooth;
using InTheHand.Net.Sockets;
using System.Threading;


namespace NewHMIBth
{
    public partial class Form1 : Form
    {
        private BluetoothListener Listener;
        private List<BluetoothClient> clientList = new List<BluetoothClient>();
        private bool listening = true;
        public Form1()
        {
            InitializeComponent();
            btnSend.Enabled = false;
            btnStop.Enabled = false;
        }
        private delegate void SafeWinFormsThreadDelegate(string msg);
        private void WriteMsg(string msg)
        {
            SafeWinFormsThreadDelegate d = new SafeWinFormsThreadDelegate(UpdateUI);
            Invoke(d, new object[] { msg });
        }
        private void UpdateUI(string msg)
        {
            this.listBoxMsg.Items.Add(msg);
        }

        private void btnStart_Click(object sender, EventArgs e)
        {
            BluetoothRadio radio = BluetoothRadio.PrimaryRadio;
            if (radio == null)
            {
                UpdateUI("没有发现蓝牙设备或者不支持蓝牙协议栈!");
                return;
            }
            radio.Mode = RadioMode.Discoverable;
            Listener = new BluetoothListener(BluetoothService.SerialPort);
            Listener.Start();
            listening = true;
            Thread ListenerThread = new Thread(ListenLoop);
            ListenerThread.Start();
            btnStop.Enabled = true;
            btnStart.Enabled = false;
            btnSend.Enabled = true;
            UpdateUI("蓝牙服务开始!");
        }
        private void ListenLoop()
        {
            string dataToSend = "感谢您的蓝牙信息订阅\r\n";
            byte[] dataBuffer = System.Text.Encoding.Unicode.GetBytes(dataToSend);
            while (listening)
            {
                try
                {
                    BluetoothClient Client = Listener.AcceptBluetoothClient();
                    WriteMsg("获得从" + Client.RemoteMachineName + "蓝牙信息订阅");
                    clientList.Add(Client);
                    System.IO.Stream ns = Client.GetStream();
                    ns.Write(dataBuffer, 0, dataBuffer.Length);
                }
                catch
                {
                    break;
                }
            }
            Listener.Stop();
        }

        private void btnSend_Click(object sender, EventArgs e)
        {
            BroadLoop(this.txtMsg.Text);
        }
        private void BroadLoop(string Msg)
        {
            List<BluetoothClient> tempClientList = new List<BluetoothClient>();
            string dataSend = "蓝牙发送的信息内容:" + Msg + "\r\n";
            Byte[] dataBuffer = System.Text.Encoding.Unicode.GetBytes(dataSend);
            foreach (BluetoothClient client in clientList)
            {
                try
                {
                    System.IO.Stream ns = client.GetStream();
                    ns.Write(dataBuffer, 0, dataBuffer.Length);
                    UpdateUI("蓝牙信息发送以出去");
                }
                catch
                {
                    tempClientList.Add(client);
                    continue;
                }
            }
            foreach (BluetoothClient client in tempClientList)
            {
                clientList.Remove(client);
            }
        }

        private void btnStop_Click(object sender, EventArgs e)
        {
            if (Listener != null)
            {
                Listener.Stop();
            }
            UpdateUI("服务停止!");
            btnSend.Enabled = false;
            btnStart.Enabled = true;
            btnStop.Enabled = false;
        }

        private void btnDiscover_Click(object sender, EventArgs e)
        {
            BluetoothRadio radio = BluetoothRadio.PrimaryRadio;
            if (radio == null)
            {
                UpdateUI("没有发现蓝牙设备或者不支持蓝牙协议栈");
                return;
            }
            radio.Mode = RadioMode.Discoverable;
            this.toolStripStatusLabel1.Text = "正在搜索蓝牙设备";
            Application.DoEvents();
            BluetoothClient Client = new BluetoothClient();
            BluetoothDeviceInfo[] BthDevies = Client.DiscoverDevices();
            cbDevices.DataSource = BthDevies;
            cbDevices.DisplayMember = "DeviceName";
            cbDevices.ValueMember = "DeviceAddress";
            this.toolStripStatusLabel1.Text = "蓝牙设备搜索完毕";
            Application.DoEvents();
        }

        private void btnSkip_Click(object sender, EventArgs e)
        {
            OpenFileDialog OFD = new OpenFileDialog();
            if (OFD.ShowDialog() == DialogResult.OK)
            {
                this.txtUpFile.Text = OFD.FileName;
            }
        }

        private void btnSendFile_Click(object sender, EventArgs e)
        {
            if (cbDevices.SelectedIndex < 0)
            {
                MessageBox.Show("请选择发送的蓝牙设备");
                return;
            }
            if (this.txtUpFile.Text.Trim() == "")
            {
                MessageBox.Show("请选择文件在发送");
                return;
            }
            ObexWebResponse Response = null;
            try
            {
                System.Uri uri = new Uri("obex://" + cbDevices.SelectedValue.ToString() + "/" + System.IO.Path.GetFileName(txtUpFile.Text));
                ObexWebRequest Request = new ObexWebRequest(uri);
                Request.ReadFile(txtUpFile.Text);
                Response = (ObexWebResponse)Request.GetResponse();
                MessageBox.Show(Response.StatusCode.ToString());
            }
            catch
            {
                MessageBox.Show("传输失败");
            }
            finally
            {
                if (Response != null)
                {
                    Response.Close();
                }
            }
        }

        private void tabControl1_SelectedIndexChanged(object sender, EventArgs e)
        {

        }

    }
}