using System;
using System.Globalization;

namespace Raytheon.Common.PdelWriter
{
   public static class PdelDataFormatter
   {
      #region Public Members
      /// <summary>
      /// Formats the specified measurement data type.
      /// </summary>
      /// <param name="measuredValue">The measured value.</param>
      /// <returns>Returns a properly formatted string.</returns>
      public static string Format(string measuredValue)
      {
         string prefix = string.Empty;

         string extension = string.Empty;

         double value;

         DateTime datetime = default(DateTime);

         if (double.TryParse(measuredValue, out value))
         {
            prefix = "R";

            if (measuredValue.IndexOf('.') != -1)
            {
               extension = measuredValue.Substring(measuredValue.IndexOf('.') + 1).Length.ToString(CultureInfo.CurrentCulture);
            }
            else
            {
               // If we don't have a decimal point it must have converted to an integer value.
               prefix = "I";
               extension = measuredValue.Length.ToString(CultureInfo.CurrentCulture);
            }
         }
         else if (DateTime.TryParse(measuredValue, out datetime))
         {
            prefix = "T";
            extension = string.Empty;
         }
         else
         {
            try
            {
               int dummy = Convert.ToInt32(measuredValue, 16);

               prefix = "H";
               extension = measuredValue.Length.ToString(CultureInfo.CurrentCulture);
            }
            catch (Exception)
            {
               prefix = "S";
               extension = measuredValue.Length.ToString(CultureInfo.CurrentCulture);
            }
         }

         return prefix + extension;
      }

      /// <summary>
      /// Determines whether [is null or empty] [the specified units].
      /// </summary>
      /// <param name="units">The units.</param>
      /// <returns>Returns a string value for the units.</returns>
      public static string IsNullOrEmpty(this string units)
      {
         var returnValue = "NONE";

         if (!string.IsNullOrEmpty(units))
         {
            returnValue = units;
         }

         return returnValue;
      }
      #endregion
   }
}