﻿using System;
using EndlessWorlds.Lib.Networking.Packets;
using EndlessWorlds.Lib.Networking.Security;
using EndlessWorlds.Lib.IO;
using EndlessWorlds.Lib.Serialization.Attributes;
using EndlessWorlds.Server.Networking.Connections;

namespace EndlessWorlds.Server.Networking.Packets.ServerPackets
{
    /// <summary>
    /// The server sends this to the client after the connection is established.<para/>
    /// This packet contains the RSA public key of the server for the duration of this connection.
    /// </summary>
    [DataContract]
    [PacketId(0x04, PacketTypes.ServerPacket)]
    public class HandshakeServerPacket : PacketBase
    {
        [DataMember] public byte[] RsaPublicKey;

        public override void Handle(Connection connection)
        {
            Logger.Debug("Server initiating handshake..");

            if (connection.ConnectionData.KeyPair != null)
                throw new Exception("Encryption key already initialized.");

            // generate our keys
            connection.ConnectionData.KeyPair = KeyPair.GenerateKeyPair();
            // initialize the decryptor
            connection.ConnectionData.Cryptor = new RSA
            {
                DecryptionKey = System.Text.Encoding.ASCII.GetString(connection.ConnectionData.KeyPair.PrivateKey)
            };

            // send the public key so the client can encrypt with it
            RsaPublicKey = connection.ConnectionData.KeyPair.PublicKey;
        }
    }
}
