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

using System;
using System.Collections.Generic;
using System.Text;

using IcqSharp.Base;
using IcqSharp.Util;

namespace IcqSharp.Packets
{
    [SnacPacketType (0x0004, 0x0007)]
    class SrvIcbmClient : PacketHandler
    {
        public SrvIcbmClient(Session session, SnacPacket packet)
            : base (session, packet)
        {
            //UInt64 msg_cookie = LittleEndianBitConverter.Big.ToUInt64 (packet.Data, 0);
            ushort msg_type = LittleEndianBitConverter.Big.ToUInt16 (packet.Data, 8);
            int uin_length = (int)packet.Data [10];

            string uin = Encoding.UTF8.GetString (packet.Data, 11, uin_length);
            //ushort warn_level = LittleEndianBitConverter.Big.ToUInt16 (packet.Data, 11 + uin_length);
            //ushort tlv_count = LittleEndianBitConverter.Big.ToUInt16 (packet.Data, 13 + uin_length);

            Log.Debug ("We received a message of type '{0}' from '{1}'!", msg_type, uin);

            int offset = 15 + uin_length;

            TlvList tlvs = TlvList.Parse(packet.Data, offset, packet.Data.Length - offset);

            if (tlvs[0x02] != null)
            {
                ParseMessage(uin, tlvs [0x02].Data);
            }
        }

        private void ParseMessage (string uin, byte[] data)
        {
            ushort capabilities_length = LittleEndianBitConverter.Big.ToUInt16 (data, 2);
            ushort msg_tlv_length = LittleEndianBitConverter.Big.ToUInt16 (data, 6 + capabilities_length);

            string message;
            // Kódování -> pokud obsahuje diakritiku je to UTF16 s BigEndian, pokud ji neobsahuje je to UTF8
            if (data[11] == 0x02)
                message = Encoding.BigEndianUnicode.GetString(data, 12 + capabilities_length, msg_tlv_length - 4);
            else
                message = Encoding.UTF8.GetString(data, 12 + capabilities_length, msg_tlv_length - 4);

            Contact c = Session.ContactList [uin];

            if (c == null)
                c = new Contact (uin);
            
            Log.Debug("Message ({0}): {1}", c.Nickname, message);

            Log.Debug(BitConverter.ToString(data));

            Message m = new Message(c, MessageType.Incoming, message);            
            Session.Messaging.OnMessageReceived(m);
        }

        /*public override FlapPacket Response(FlapPacket packet)
        {
            CliIcbmSendAck ack = new CliIcbmSendAck (uin, "Som off :D");
            return ack;
        }*/
    }
}
