using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using skyscraper5.Mpeg2;
using skyscraper5.Skyscraper.IO;
using skyscraper5.Skyscraper.Plugins;
using skyscraper5.Skyscraper.Text;

namespace skyscraper5.Dvb.Descriptors.Extension
{
	/**
     * create table public.dvb_sdt_messages
        (
            tsid          integer                             not null,
            onid          integer                             not null,
            sid           integer                             not null,
            msgid         integer                             not null,
            language_code varchar(3)                          not null,
            message       text                                not null,
            dateadded     timestamp default current_timestamp not null,
            constraint dvb_sdt_messages_pk
                primary key (tsid, onid, sid, msgid),
            constraint dvb_sdt_messages_dvb_sdt_tsid_onid_sid_fk
                foreign key (tsid, onid, sid) references public.dvb_sdt
        );
*/
	[SkyscraperPlugin]
	[ExtensionDescriptor(0x08,"NIT","BAT","SDT","EIT")]
    public class MessageDescriptor : Dvb.ExtensionDescriptor
    {
        public MessageDescriptor(byte[] buffer)
        {
            if (buffer == null)
            {
                Valid = false;
                return;
            }

            MemoryStream ms = new MemoryStream(buffer, false);
            MessageId = ms.ReadUInt8();
            Iso639LanguageCode = Encoding.ASCII.GetString(ms.ReadBytes(3));
            Message = En300468AnnexATextDecoder.GetInstance().Decode(ms.ReadBytes(ms.GetAvailableBytes()));
        }

        public string Message { get; set; }

        public string Iso639LanguageCode { get; set; }

        public byte MessageId { get; set; }

        protected bool Equals(MessageDescriptor other)
        {
            return Message == other.Message && Iso639LanguageCode == other.Iso639LanguageCode;
        }

        public override bool Equals(object obj)
        {
            if (ReferenceEquals(null, obj)) return false;
            if (ReferenceEquals(this, obj)) return true;
            if (obj.GetType() != this.GetType()) return false;
            return Equals((MessageDescriptor)obj);
        }

        public override int GetHashCode()
        {
            return HashCode.Combine(Message, Iso639LanguageCode);
        }

        public override string ToString()
        {
            return $"{nameof(MessageId)}: {MessageId}, {nameof(Message)}: {Message}";
        }
    }
}
