/* 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 PopularimeterFrame : ID3v2Frame
    {
        public PopularimeterFrame()
            : base("POPM", 0, 0, null)
        { }
        public PopularimeterFrame(int size, ushort flags, byte[] data)
            : base("POPM", size, flags, data)
        { }
        public override string Name
        {
            get { return "Popularimeter"; }
        }

        string email = "";
        byte rating = 0;
        int counter = 0;
        public string Email
        { get { return email; } set { email = value; } }
        public byte Rating
        { get { return rating; } set { rating = value; } }
        public int Counter
        { get { return counter; } set { counter = value; } }
        public override int GetSize()
        {
            return ID3v2EncodingWrapper.ISO_8859_1.GetByteCount(email + "\0") + 1 + (counter == 0 ? 0 : 4);
        }

        public override void Load()
        {
            string[] Ltext = ID3v2EncodingWrapper.ISO_8859_1.GetString(Data, 0, Data.Length).Split(new char[] { '\0' });
            email = Ltext[0];
            int index = email.Length + 1;
            rating = Data[index]; index++;
            if ((Data.Length - index) == 4)//sometimes this frame doesn't save counter at all ...
                counter = SynchsafeConvertor.FromBytes(new byte[] 
                { Data[index], Data[index+1],
                  Data[index+2], Data[index+3] });
            else
                counter = 0;
        }

        public override void Save()
        {
            List<byte> data = new List<byte>();
            //email
            data.AddRange(ID3v2EncodingWrapper.ISO_8859_1.GetBytes(email + "\0"));
            //rating
            data.Add(rating);
            //counter
            if (counter > 0)
                data.AddRange(SynchsafeConvertor.ToInt32Bytes(counter));
            //save
            this.Data = data.ToArray();
        }

        public override string ToString()
        {
            return email + " [rating=" + rating.ToString() +
                ", counter=" + counter + "]";
        }
    }
}
