using System;
using System.IO;
using System.Text;
namespace NAudio.Midi 
{
    /// 
    /// Represents a MIDI pitch wheel change event
    /// 
    public class PitchWheelChangeEvent : MidiEvent 
    {
        private int pitch;
        
        /// 
        /// Reads a pitch wheel change event from a MIDI stream
        /// 
        /// The MIDI stream to read from
        public PitchWheelChangeEvent(BinaryReader br) 
        {
            byte b1 = br.ReadByte();
            byte b2 = br.ReadByte();
            if((b1 & 0x80) != 0) 
            {
                // TODO: might be a follow-on				
                throw new FormatException("Invalid pitchwheelchange byte 1");
            }
            if((b2 & 0x80) != 0) 
            {
                throw new FormatException("Invalid pitchwheelchange byte 2");
            }
            
            pitch = b1 + (b2 << 7); // 0x2000 is normal
        }
        /// 
        /// Creates a new pitch wheel change event
        /// 
        /// Absolute event time
        /// Channel
        /// Pitch wheel value
        public PitchWheelChangeEvent(long absoluteTime, int channel, int pitchWheel)
            : base(absoluteTime, channel, MidiCommandCode.PitchWheelChange)
        {
            Pitch = pitchWheel;
        }
        
        /// 
        /// Describes this pitch wheel change event
        /// 
        /// String describing this pitch wheel change event
        public override string ToString() 
        {
            return String.Format("{0} Pitch {1} ({2})",
                base.ToString(),
                this.pitch,
                this.pitch - 0x2000);
        }
        /// 
        /// Pitch Wheel Value 0 is minimum, 0x2000 (8192) is default, 0x3FFF (16383) is maximum
        /// 
        public int Pitch
        {
            get
            {
                return pitch;
            }
            set
            {
                if (value < 0 || value >= 0x4000)
                {
                    throw new ArgumentOutOfRangeException("value", "Pitch value must be in the range 0 - 0x3FFF");
                }
                pitch = value;
            }
        }
        /// 
        /// Gets a short message
        /// 
        /// Integer to sent as short message
        public override int GetAsShortMessage()
        {
            return base.GetAsShortMessage() + ((pitch & 0x7f) << 8) + (((pitch >> 7) & 0x7f) << 16);
        }
        /// 
        /// Calls base class export first, then exports the data 
        /// specific to this event
        /// MidiEvent.Export
        /// 
        public override void Export(ref long absoluteTime, BinaryWriter writer)
        {
            base.Export(ref absoluteTime, writer);
            writer.Write((byte)(pitch & 0x7f));
            writer.Write((byte)((pitch >> 7) & 0x7f));
        }
    }
}