// <auto-generated/>
// ReSharper disable All

namespace MyTelegram.Schema;

///<summary>
/// Reply to an external message
/// See <a href="https://corefork.telegram.org/constructor/inputReplyToExternalMessage" />
///</summary>
[TlObject(0x869fbe10)]
public sealed class TInputReplyToExternalMessage : IInputReplyTo
{
    public uint ConstructorId => 0x869fbe10;
    
    ///<summary>
    /// Flags, see <a href="https://corefork.telegram.org/mtproto/TL-combinators#conditional-fields">TL conditional fields</a>
    ///</summary>
    public int Flags { get; set; }

    ///<summary>
    /// The peer to which the external message belongs
    /// See <a href="https://corefork.telegram.org/type/InputPeer" />
    ///</summary>
    public MyTelegram.Schema.IInputPeer Peer { get; set; }

    ///<summary>
    /// The message ID
    ///</summary>
    public int MsgId { get; set; }

    ///<summary>
    /// Used to quote-reply to only a certain section (specified here) of the original message.
    ///</summary>
    public string? QuoteText { get; set; }

    ///<summary>
    /// Message entities for styled text from the quote_text field.
    ///</summary>
    public TVector<MyTelegram.Schema.IMessageEntity>? QuoteEntities { get; set; }

    ///<summary>
    /// Offset of the message quote_text within the original message
    ///</summary>
    public int? QuoteOffset { get; set; }

    public void ComputeFlag()
    {
        if (QuoteText != null) { Flags = Flags.SetBit(0); }
        if (QuoteEntities?.Count > 0) { Flags = Flags.SetBit(1); }
        if (/*QuoteOffset != 0 && */QuoteOffset.HasValue) { Flags = Flags.SetBit(2); }
    }

    public void Serialize(IBufferWriter<byte> writer)
    {
        ComputeFlag();
        writer.Write(ConstructorId);
        writer.Write(Flags);
        writer.Write(Peer);
        writer.Write(MsgId);
        if (Flags.IsBitSet(0)) { writer.Write(QuoteText); }
        if (Flags.IsBitSet(1)) { writer.Write(QuoteEntities); }
        if (Flags.IsBitSet(2)) { writer.Write(QuoteOffset.Value); }
    }

    public void Deserialize(ref ReadOnlyMemory<byte> buffer)
    {
        Flags = buffer.ReadInt32();
        Peer = buffer.Read<MyTelegram.Schema.IInputPeer>();
        MsgId = buffer.ReadInt32();
        
        // Only read optional fields if there's enough data in the buffer
        try
        {
            if (Flags.IsBitSet(0) && buffer.Length > 0) { QuoteText = buffer.ReadString(); }
            if (Flags.IsBitSet(1) && buffer.Length > 0) { QuoteEntities = buffer.Read<TVector<MyTelegram.Schema.IMessageEntity>>(); }
            if (Flags.IsBitSet(2) && buffer.Length >= 4) { QuoteOffset = buffer.ReadInt32(); }
        }
        catch (ArgumentException)
        {
            // Ignore if optional fields cannot be read due to insufficient buffer
        }
    }
}
