using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace EMDServer.Util
{
    class Utils
    {
        private static Utils utils;

        /// <summary>
        /// Private constructor of the class --> Singleton
        /// </summary>
        private Utils()
        {
        }

        /// <summary>
        /// Returns an instance of the class
        /// </summary>
        /// <returns>Utils instance</returns>
        public static Utils getInstance()
        {
            if (utils == null)
            {
                utils = new Utils();
            }

            return utils;
        }

        /// <summary>
        /// Method to convert hex string into a byte array
        /// </summary>
        /// <param name="msg">string to convert</param>
        /// <returns>a byte array</returns>
        public byte[] HexToByte(String msg)
        {
            // create a byte array the length of the string 
            byte[] comBuffer = new byte[msg.Length];

            // loop through the length of the provided string
            for (int i=0; i<msg.Length; i++)
            {
                // convert each character to a byte    
                // and add to the array
                comBuffer[i] = (byte)Convert.ToByte(msg.Substring(i, 1), 8);
            }

            // return the array
            return comBuffer;
        }

        /// <summary>
        /// Mlethod to convert a byte array into a hex string
        /// </summary>
        /// <param name="comByte">byte array to convert</param>
        /// <returns>a hex string</returns>
        public String ByteToHex(byte[] comBuffer)
        {
            // create a new StringBuilder object
            StringBuilder builder = new StringBuilder(comBuffer.Length * 3);

            // loop through each byte in the array
            foreach (byte data in comBuffer)
            {
                // convert the byte to a string and add to the stringbuilder
                builder.Append(Convert.ToString(data, 8));
            }

            // return the converted value
            return builder.ToString();
        }

        public int ConvertByteToDecimal(byte[] value)
        {
            Int32 result = 0;
            for (int i = 0; i < value.Length; i++)
            {
                result += (int) Math.Pow(10, value.Length - i -1) * (int)value[i];
            }
            return result;
        }
    }
}
