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 Currency : INullable, IBinarySerialize
{
  private bool m_Null;

  private string currencyCode;
  private decimal amount;

  public string CurrencyCode
  { get { return currencyCode; } set { currencyCode = value; } }

  public decimal Amount
  { get { return amount; } set { amount = value; } }

  public override string ToString()
  {
    if (m_Null)
      return "null";
    else
      return String.Format("{0} ({1})", amount, currencyCode);
  }

  public bool IsNull
  {
    get
    {
      return m_Null;
    }
  }

  public static Currency Null
  {
    get
    {
      Currency currency = new Currency();
      currency.m_Null = true;
      return currency;
    }
  }

  public static Currency Parse(SqlString s)
  {
    if (s.IsNull || s.Value.ToLower().Equals("null"))
      return Null;
    Currency currency = new Currency();
    string[] st = s.Value.Split(' ');
    currency.Amount = decimal.Parse(st[0]);
    currency.CurrencyCode = st[1];
    currency.m_Null = false;
    return currency;
  }

  public void Write(System.IO.BinaryWriter w)
  {
    w.Write(amount);
    w.Write(currencyCode);
  }

  public void Read(System.IO.BinaryReader r)
  {
    amount = r.ReadDecimal();
    currencyCode = r.ReadString();
  }
}


