//          Copyright Jens Granlund 2012.
//      Distributed under the New BSD License.
//     (See accompanying file notice.txt or at 
// http://www.opensource.org/licenses/bsd-license.php)
// Source: https://bitbucket.org/jens13/cleanzip

using System;

namespace CleanZip.Compression
{
    public class WinZipAesExtra : IZipExtraField
    {
        public const ushort HeaderId = 0x9901;
        
        private readonly byte[] _buffer = new byte[] { 0x01, 0x99, 0x07, 0x00, 0x02, 0x00, 0x41, 0x45, 0x03, 0x00, 0x00 };

        public WinZipAesExtra(CompressionType compressionMethod)
        {
            CompressionMethod = compressionMethod;
        }

        public WinZipAesExtra(byte[] buffer)
        {
            if (buffer[2] != 0x07) throw new WinZipAesException();
            if (buffer[3] != 0x00) throw new WinZipAesException();
            if (buffer[5] != 0x00) throw new WinZipAesException();
            if (buffer[6] != 0x41) throw new WinZipAesException();
            if (buffer[7] != 0x45) throw new WinZipAesException();
            if (buffer[10] != 0x00) throw new WinZipAesException();
            _buffer[4] = buffer[4];
            _buffer[8] = buffer[8];
            _buffer[9] = buffer[9];
        }

        public CompressionType CompressionMethod { get { return (CompressionType)_buffer[9]; } set { _buffer[9] = (byte)value; } }
        public WinZipAesType Vendor { get { return (WinZipAesType)_buffer[4]; } set { _buffer[4] = (byte)value; } }
        public WinZipAesKeyStrength KeyStrength { get { return (WinZipAesKeyStrength)_buffer[8]; } set { _buffer[8] = (byte)value; } }

        public byte[] ToArray()
        {
            var buffer = new byte[11];
            Buffer.BlockCopy(_buffer,0,buffer,0, 11);
            return buffer;
        }
    }
}