#region Using directives

using System;
using System.Drawing;
using System.Collections;
using System.Windows.Forms;
using System.Data;
using System.Net;
using System.Net.Sockets;
using System.IO;

#endregion

namespace IrDA_Smartphone_CS
{
    /// <summary>
    /// Summary description for form.
    /// </summary>
    public class Form1 : System.Windows.Forms.Form
    {
        private ComboBox comboBox1;
        private MenuItem mnuDiscovery;
        private MenuItem menuItem1;
        private MenuItem mnuSend;
        private MenuItem mnuReceive;
        /// <summary>
        /// Main menu for the form.
        /// </summary>
        private System.Windows.Forms.MainMenu mainMenu1;

        private IrDAListener irListen;
        private IrDAClient irClient;
        private IrDAEndPoint irEndP;
        private IrDADeviceInfo[] irDevices;

        string fileSend;
        string fileReceive;
        string irServiceName;
        private Label label1;

        int buffersize;

        public Form1()
        {
            InitializeComponent();
            irClient = new IrDAClient();

            // Files for sending and receiving.
            fileSend = ".\\My Documents\\send.txt";
            fileReceive = ".\\My Documents\\receive.txt";

            // Specify a name for the IrDA Service.
            // It can be any name, provided all
            // participating devices use the same name.
            irServiceName = "IrDA";

            // Set maximum buffer size for file transfers.
            buffersize = 256;

            
            // Disable Send and Receive buttons until devices are discovered.
            mnuSend.Enabled = false;
            mnuReceive.Enabled = false;
        }

        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        protected override void Dispose(bool disposing)
        {
            base.Dispose(disposing);
        }

        #region Windows Form Designer generated code
        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this.mainMenu1 = new System.Windows.Forms.MainMenu();
            this.comboBox1 = new System.Windows.Forms.ComboBox();
            this.mnuDiscovery = new System.Windows.Forms.MenuItem();
            this.menuItem1 = new System.Windows.Forms.MenuItem();
            this.mnuSend = new System.Windows.Forms.MenuItem();
            this.mnuReceive = new System.Windows.Forms.MenuItem();
            this.label1 = new System.Windows.Forms.Label();
            // 
            // mainMenu1
            // 
            this.mainMenu1.MenuItems.Add(this.mnuDiscovery);
            this.mainMenu1.MenuItems.Add(this.menuItem1);
            // 
            // comboBox1
            // 
            this.comboBox1.Location = new System.Drawing.Point(3, 22);
            this.comboBox1.Size = new System.Drawing.Size(152, 28);
            // 
            // mnuDiscovery
            // 
            this.mnuDiscovery.Text = "Найти ус-ва";
            this.mnuDiscovery.Click += new System.EventHandler(this.mnuDiscovery_Click);
            // 
            // menuItem1
            // 
            this.menuItem1.MenuItems.Add(this.mnuSend);
            this.menuItem1.MenuItems.Add(this.mnuReceive);
            this.menuItem1.Text = "Команды";
            // 
            // mnuSend
            // 
            this.mnuSend.Text = "Послать";
            this.mnuSend.Click += new System.EventHandler(this.mnuSend_Click);
            // 
            // mnuReceive
            // 
            this.mnuReceive.Text = "Принять";
            this.mnuReceive.Click += new System.EventHandler(this.mnuReceive_Click);
            // 
            // label1
            // 
            this.label1.Location = new System.Drawing.Point(3, 154);
            this.label1.Size = new System.Drawing.Size(170, 25);
            // 
            // Form1
            // 
            this.ClientSize = new System.Drawing.Size(176, 180);
            this.Controls.Add(this.comboBox1);
            this.Controls.Add(this.label1);
            this.Menu = this.mainMenu1;
            this.Text = "Form1";

        }

        #endregion

        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        static void Main()
        {
            Application.Run(new Form1());
        }

        private void mnuDiscovery_Click(object sender, EventArgs e)
        {
            // Discover and list the available infrared devices.
            // Infrared ports must be aligned.
            // Create a collection of a maximum of three devices.
            irDevices = irClient.DiscoverDevices(2);

            // Show a message if no devices are found.
            if (irDevices.Length == 0)
            {
                MessageBox.Show("No remote infrared devices found!");
                return;
            }

            // Enumerate the IrDADeviceInfo
            // array and list device information
            // for each device in the list box.
            string device;
            int ID;
            comboBox1.Items.Clear();
            foreach (IrDADeviceInfo irDevice in irDevices)
            {
                ID = BitConverter.ToInt32(irDevice.DeviceID, 0);
                device = ID.ToString() + " " + irDevice.DeviceName + " "
                    + irDevice.CharacterSet + " " + irDevice.Hints;
                comboBox1.Items.Add(device);
            }

            comboBox1.SelectedIndex = 0;
            if (irDevices.Length > 0)
                


            // Enable the Send and Receive buttons.
            mnuSend.Enabled = true;
            mnuReceive.Enabled = true;
        }

        private void mnuSend_Click(object sender, EventArgs e)
        {
            // Open the file to send and get its stream.
            Stream fileStream;
            try
            {
                fileStream = new FileStream(fileSend, FileMode.Open);
            }
            catch (Exception exFile)
            {
                MessageBox.Show("Cannot open " + exFile.ToString());
                return;
            }

            // Create an IrDA client with a service name that must
            // match the service name of the receiving IrDA client.
            try
            {
                irClient = new IrDAClient(irServiceName);
            }
            catch (SocketException exS)
            {
                MessageBox.Show("Create socket error: " + exS.Message +
                    " - Did you click Receive on the other device?");
                return;
            }

            // Get the underlying stream of the client.
            Stream baseStream = irClient.GetStream();

            // Get the size of the file to send
            // and write its size to the stream.
            byte[] length = BitConverter.GetBytes((int)fileStream.Length);
            baseStream.Write(length, 0, length.Length);

            // Create a buffer for reading the file.
            byte[] buffer = new byte[buffersize];

            // Display the number of bytes being sent.
            int fileLength = (int)fileStream.Length;
            label1.Text = "Sending " + fileLength + " bytes";

            // Read the file stream into the base stream.
            while (fileLength > 0)
            {
                int numRead = fileStream.Read(buffer, 0, buffer.Length);
                baseStream.Write(buffer, 0, numRead);
                fileLength -= numRead;
            }

            fileStream.Close();
            baseStream.Close();
            irClient.Close();
        }

        private void mnuReceive_Click(object sender, EventArgs e)
        {
            // Create a stream for writing the file.
            Stream writeStream;
            try
            {
                writeStream = new FileStream(fileReceive,
                    FileMode.OpenOrCreate);
            }
            catch (Exception)
            {
                MessageBox.Show("Couldn't open "
                    + fileReceive + " for writing");
                return;
            }

            // Create a connection, with the IrDAEndPoint class,
            // for the selected device in the list box.
            // Start listening for incoming requests from
            // that device with an IrDAListener object.
            try
            {
                int i = comboBox1.SelectedIndex;
                irEndP = new IrDAEndPoint(irDevices[i].DeviceID,
                    irServiceName);
                irListen = new IrDAListener(irEndP);
                irListen.Start();
            }
            catch (SocketException exSoc)
            {
                MessageBox.Show("Couldn't listen on service "
                    + irServiceName + ": "
                    + exSoc.ErrorCode);
            }

            // Show listening for selected device.
            label1.Text = "Listening for "
                + comboBox1.SelectedItem.ToString();

            // Create a client connection for the
            // service detected by the listener.
            IrDAClient irClient;
            try
            {
                irClient = irListen.AcceptIrDAClient();
            }
            catch (SocketException exp)
            {
                MessageBox.Show("Couldn't accept socket "
                    + exp.ErrorCode);
                return;
            }

            

            // Get the underlying stream of the client.
            Stream baseStream = irClient.GetStream();

            int numToRead;

            // Create a buffer for reading the file.
            byte[] buffer = new byte[buffersize];

            // Read the stream of data, which contains
            // the data from the remote device, until
            // there are no more bytes to read.
            numToRead = 4;
            while (numToRead > 0)
            {
                int numRead = baseStream.Read(buffer, 0, numToRead);
                numToRead -= numRead;
            }

            // Get the size of the buffer to show
            // the number of bytes to write to the file.
            numToRead = BitConverter.ToInt32(buffer, 0);
            

            // Write the stream to the file until
            // there are no more bytes to read.
            while (numToRead > 0)
            {
                int numRead = baseStream.Read(buffer, 0, buffer.Length);
                numToRead -= numRead;
                writeStream.Write(buffer, 0, numRead);
            }

            // Show that the file was received.
            label1.Text = "File received";

            baseStream.Close();
            writeStream.Close();
            irListen.Stop();
            irClient.Close();
        }

    }
}

