/* This file is part of AHD ID3 Tag Editor (AITE)
   A program can create and edit ID3 Tag for mp3 files

   Copyright © Ala I.Hadid 2012

   This program is free software: you can redistribute it and/or modify
   it under the terms of the GNU General Public License as published by
   the Free Software Foundation, either version 3 of the License, or
   (at your option) any later version.

   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.

   You should have received a copy of the GNU General Public License
   along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace AHD.ID3Tag
{
    public class EventTimingCodesFrame : ID3v2Frame
    {
        public EventTimingCodesFrame(string name)
            : base("ETCO", 0, 0, null)
        { }
        public EventTimingCodesFrame(string id, int size, ushort flags, byte[] data)
            : base(id, size, flags, data)
        { }
        public override string Name
        {
            get { return "Event Timing Codes"; }
        }
        TimeStampFormat timeStamp = TimeStampFormat.AbsoluteMilliseconds;
        List<EventTimingItem> items = new List<EventTimingItem>();

        public List<EventTimingItem> Items
        { get { return items; } set { items = value; } }
        public TimeStampFormat TimeStamp
        { get { return timeStamp; } set { timeStamp = value; } }

        public override void Load()
        {
            timeStamp = (TimeStampFormat)Data[0];
            for (int i = 1; i < Data.Length - 1; i ++)
            {
                byte type = Data[i];
                i++;
                int time = (Data[i] << 24) | (Data[i + 1] << 16) | (Data[i + 2] << 8) | Data[i + 3];
                i += 3;
                items.Add(new EventTimingItem(time, type));
            }
        }

        public override int GetSize()
        {
            return 1 + (items.Count * 5);
        }

        public override void Save()
        {
            List<byte> data = new List<byte>();
            //timeStamp
            data.Add((byte)timeStamp);
            //items
            foreach (EventTimingItem item in items)
            {
                data.Add(item.EventType);
                //time
                data.Add((byte)((item.Time & 0xFF000000) >> 24));
                data.Add((byte)((item.Time & 0x00FF0000) >> 16));
                data.Add((byte)((item.Time & 0x0000FF00) >> 08));
                data.Add((byte)((item.Time & 0x000000FF) >> 00));
            }
            //save
            this.Data = data.ToArray();
        }
    }
}
