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

using System;
using System.Collections.Generic;

using IcqSharp.Packets;
using IcqSharp.Util;

namespace IcqSharp.Connections
{
    public delegate void LoginCompleteDelegate (ServerConnection server);

    public abstract class LoginConnection : Connection
    {
        private static string host = "login.icq.com";
        private static int port = 5190;

        protected string uin;
        protected string password;

        public event LoginCompleteDelegate LoginComplete;
        public event EventHandler LoginFailed;

        public LoginConnection (Session session, string uin, string password)
            : base (session, host, port)
        {
            this.uin = uin;
            this.password = password;
        }

        protected void GotCookie (string uin, string server, byte[] cookie)
        {
            // FIXME: This sometimes happens when we dont login correctly
            // and get banned for a little while. Handle that gracefully.
            if (this.uin != uin) {
                Log.Error ("Login response UINs do no match!");
                throw new FormatException ("Invalid UIN received");
            }

            Log.Debug("Successfuly logged in!");

            ServerConnection server_connection = new ServerConnection(Session, server.Substring(0, server.Length - 5), 5190, cookie);

            OnLoginComplete (server_connection);
        }

        protected void OnLoginComplete (ServerConnection server)
        {
            if (LoginComplete != null)
                LoginComplete (server);
        }

        protected void OnLoginFailed (object o, EventArgs args)
        {
            if (LoginFailed != null)
                LoginFailed (o, args);
        }

        protected string Uin
        {
            get { return uin; }
        }

        protected string Password
        {
            get { return password; }
        }
    }
}
