using System.Collections.ObjectModel;
using System.IO;
using UnityEngine;
namespace UnityEditor.U2D.Aseprite
{
    /// 
    /// Structure for an entry in the color palette.
    /// 
    public struct PaletteEntry
    {
        internal PaletteEntry(string name, Color32 color)
        {
            this.name = name;
            this.color = color;
        }
        /// 
        /// Name of the color.
        /// 
        public string name { get; private set; }
        /// 
        /// Color value.
        /// 
        public Color32 color { get; private set; }
    }
    /// 
    /// Parsed representation of an Aseprite Palette chunk.
    /// 
    public class PaletteChunk : BaseChunk, IPaletteProvider
    {
        /// 
        public override ChunkTypes chunkType => ChunkTypes.Palette;
        /// 
        /// Number of entries in the palette.
        /// 
        public uint noOfEntries { get; private set; }
        /// 
        /// Index of the first color to change.
        /// 
        public uint firstColorIndex { get; private set; }
        /// 
        /// Index of the last color to change.
        /// 
        public uint lastColorIndex { get; private set; }
        /// 
        /// Array of palette entries.
        /// 
        public ReadOnlyCollection entries => System.Array.AsReadOnly(m_Entries);
        PaletteEntry[] m_Entries;
        internal PaletteChunk(uint chunkSize) : base(chunkSize) { }
        /// 
        /// Read and store the chunk data.
        /// 
        /// The active binary reader of the file.
        protected override void InternalRead(BinaryReader reader)
        {
            noOfEntries = reader.ReadUInt32();
            firstColorIndex = reader.ReadUInt32();
            lastColorIndex = reader.ReadUInt32();
            // Reserved bytes
            for (var i = 0; i < 8; ++i)
                reader.ReadByte();
            m_Entries = new PaletteEntry[noOfEntries];
            for (var i = 0; i < noOfEntries; ++i)
            {
                var entryFlag = reader.ReadUInt16();
                var red = reader.ReadByte();
                var green = reader.ReadByte();
                var blue = reader.ReadByte();
                var alpha = reader.ReadByte();
                var color = new Color32(red, green, blue, alpha);
                var name = "";
                var hasName = entryFlag == 1;
                if (hasName)
                    name = AsepriteUtilities.ReadString(reader);
                m_Entries[i] = new PaletteEntry(name, color);
            }
        }
    }
}