/* 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 UserDefinedURLLinkFrame : ID3v2Frame
    {
        public UserDefinedURLLinkFrame()
            : base("WXXX", 0, 0, null)
        { }
        public UserDefinedURLLinkFrame(int size, ushort flags, byte[] data)
            : base("WXXX", size, flags, data)
        { }
        public override string Name
        {
            get { return "User defined URL link frame"; }
        }
        string url = "";
        string desc = "";
        Encoding encoding = ID3v2EncodingWrapper.ISO_8859_1;
        void DetectEncoding(string val)
        {
            if (encoding.CodePage == ID3v2EncodingWrapper.ISO_8859_1.CodePage)
                encoding = ID3v2EncodingWrapper.GetBestEncoding(val);
        }
        public virtual Encoding Encoding
        { get { return encoding; } set { encoding = value; } }
        public virtual string URL
        { get { return url; } set { url = value; } }
        public virtual string Description
        { get { return desc; } set { desc = value; DetectEncoding(value); } }

        public override void Load()
        {
            encoding = ID3v2EncodingWrapper.FromByte(Data[0]);
            string[] Ltext = encoding.GetString(Data, 1, Data.Length - 1).Split(new char[] { '\0' });
            int index = 1;
            desc = Ltext[0];
            index += encoding.GetByteCount(desc + "\0");

            url = ID3v2EncodingWrapper.ISO_8859_1.GetString(Data, index, Data.Length - index);
        }
        public override int GetSize()
        {
            return 1 + encoding.GetByteCount(desc + "\0") + ID3v2EncodingWrapper.ISO_8859_1.GetByteCount(url);
        }
        public override void Save()
        {
            List<byte> data = new List<byte>();
            //encoding
            data.Add(ID3v2EncodingWrapper.ToByte(encoding));
            //desc
            data.AddRange(encoding.GetBytes(desc + "\0"));
            //url
            data.AddRange(ID3v2EncodingWrapper.ISO_8859_1.GetBytes(url));
            //save
            this.Data = data.ToArray();
        }
    }
}
