﻿namespace Wol
{
    using System;
    using System.Collections.Generic;
    using System.Net;
    using System.Net.Sockets;

    class Program
    {
        /// <summary>
        /// Точка входа.
        /// </summary>
        /// <param name="macAddressCollection">
        /// The mac address collection.
        /// </param>
        static void Main(string[] macAddressCollection)
        {
            if (macAddressCollection.Length == 0)
            {
                WriteHelp();
                return;
            }

            using (var udpClient = new UdpClient())
            {
                var ipEndPoint = new IPEndPoint(IPAddress.Broadcast, 9);
                foreach (var macAddress in macAddressCollection)
                {
                    byte[] magicPacket = CreateMagicPacket(macAddress);
                    udpClient.Send(magicPacket, magicPacket.Length, ipEndPoint);
                    Console.WriteLine(String.Format("Отправлен пакет включения для {0}", macAddress));
                }
            }
        }

        /// <summary>
        /// Создание магического пакета.
        /// </summary>
        /// <param name="macAddress">
        /// The mac address.
        /// </param>
        /// <returns>
        /// Магический пакет.
        /// </returns>
        private static byte[] CreateMagicPacket(string macAddress)
        {
            var magicPacket = new List<byte>(102);
 
            // Добавление "Цепочки синхронизации"
            for (int i = 0; i < 6; i++)
            {
                magicPacket.Add(0xff);
            }

            string[] macDigits = macAddress.Split(':', '-');
            if (macDigits.Length != 6)
            {
                throw new InvalidOperationException(String.Format("Неправильный формат MAC адреса: {0}", macAddress));
            }

            // Добавление MAC адресов
            for (int j = 0; j < 16; j++)
            {
                foreach (var macDigit in macDigits)
                {
                    magicPacket.Add(Convert.ToByte(macDigit, 16));
                }
            }
 
            return magicPacket.ToArray();
        }

        /// <summary>
        /// Вывод помощи.
        /// </summary>
        private static void WriteHelp()
        {
            Console.WriteLine("Необходимо задать MAC адреса.");
            Console.WriteLine("Пример использования:");
            Console.WriteLine("wol.exe 01:02:03:04:05:06 07:08:09:0A:0B:0C");
        }
    }
}
