//
// SrvIcbmSendAck.cs
//
// Copyright (c) 2007 Lukas Lipka.
//

using System;
using System.Collections.Generic;
using System.Text;
using System.Xml;
using System.Xml.XPath;

using IcqSharp.Base;
using IcqSharp.Util;

namespace IcqSharp.Packets
{
    [SnacPacketType (0x0004, 0x000B)]
    class SrvIcbmSendAck : PacketHandler
    {
        public SrvIcbmSendAck(Session session, SnacPacket packet)
            : base (session, packet)
        {
            ushort channel = LittleEndianBitConverter.Big.ToUInt16 (packet.Data, 8);
            int length = (int)packet.Data[10];
            string uin = Encoding.UTF8.GetString (packet.Data, 11, length);
            ushort reason = LittleEndianBitConverter.Big.ToUInt16(packet.Data, 11 + length);

            //Log.Debug("SrvIcbmSendAck: {0:X}", reason);
            //DebugFu.WriteBytes(packet.Data);
            //Log.Debug(xml);

            // Transform the XML string received from the server
            // because it comes in a fucked up format
            string xml = Encoding.UTF8.GetString(packet.Data, 165, packet.Data.Length - 165 - 2);
            xml = xml.Replace("&lt;", "<");
            xml = xml.Replace("&gt;", ">");

            XmlDocument doc = new XmlDocument();
            doc.LoadXml(xml);

            string title = doc.SelectSingleNode ("//title").InnerText;
            string desc = doc.SelectSingleNode("//desc").InnerText;

            Contact contact = Session.ContactList[uin];

            if (contact != null)
                Session.Messaging.OnXStatusReceived(contact, title, desc);
        }
    }
}
