using System;
using System.Data;
using System.Data.SqlClient;
using System.Data.SqlTypes;
using Microsoft.SqlServer.Server;

[Serializable]
[Microsoft.SqlServer.Server.SqlUserDefinedType(Format.UserDefined,MaxByteSize=32)]
public struct DMS : INullable, IBinarySerialize
{
  private bool m_Null;
  private byte degrees, minutes, seconds;

  public byte Degrees
  { get { return degrees; } set { degrees = value; } }

  public byte Minutes
  { get { return minutes; } set { minutes = value; } }

  public byte Seconds
  { get { return seconds; } set { seconds = value; } }

  public override string ToString()
  {
    if (m_Null)
      return "null";
    else
      return String.Format("{0}°{1}'{2}", degrees, minutes, seconds);
  }

  public bool IsNull
  {
    get
    {
      // Put your code here
      return m_Null;
    }
  }

  public static DMS Null
  {
    get
    {
      DMS dms = new DMS();
      dms.m_Null = true;
      return dms;
    }
  }

  public static DMS Parse(SqlString s)
  {
    if (s.IsNull || s.Value.ToLower().Equals("null"))
      return Null;
    DMS dms = new DMS();
    string[] st = s.Value.Split('.');
    dms.Degrees = Byte.Parse(st[0]);
    dms.Minutes = Byte.Parse(st[1]);
    dms.Seconds = Byte.Parse(st[2]);
    dms.m_Null = false;
    return dms;
  }

  public void Write(System.IO.BinaryWriter w)
  {
    w.Write(degrees);
    w.Write("D");
    w.Write(minutes);
    w.Write("M");
    w.Write(seconds);
    w.Write("S");
  }

  public void Read(System.IO.BinaryReader r)
  {
    degrees = r.ReadByte();
    r.ReadChars(2);
    minutes = r.ReadByte();
    r.ReadChars(2);
    seconds = r.ReadByte();
  }

}


