﻿using System.Net.Sockets;
using System.Threading;
using EndlessWorlds.Lib.Networking.Security;
using EndlessWorlds.Server.Data;

namespace EndlessWorlds.Server.Networking.Connections
{
    public class ConnectionData
    {
        private static long _nextConnectionId;

        private static long GetNextConnectionId => Interlocked.Increment(ref _nextConnectionId);

        /// <summary>
        /// Gets the not necessarily unique identifier of this <see cref="ConnectionData"/>.
        /// </summary>
        public long ID { get; }
        public Connection Connection { get; set; }
        public Socket Socket { get; }
        public bool IsConnected { get; set; }
        public ulong ReceivedBytes { get; set; }
        public ulong SentBytes { get; set; }

        #region Security

        public IKeyPair KeyPair { get; set; }

        public IAsymmetricCryptor Cryptor { get; set; }

        /// <summary>
        /// Key used for encrypting the data that's being sent. You encrypt with this key.
        /// </summary>
        public byte[] SymmetricEncryptionKey { get; set; }

        /// <summary>
        /// Key used for decrypting the data that's being sent. The other endpoint encrypts with this key.
        /// </summary>
        public byte[] SymmetricDecryptionKey { get; set; }

        #endregion Security

        // Account/character related
        public AccountData Account { get; set; }

        public ConnectionData(Socket socket)
        {
            ID = GetNextConnectionId;
            Socket = socket;
            IsConnected = true;
            ReceivedBytes = 0UL;
            SentBytes = 0UL;
            KeyPair = null;
            Cryptor = null;
            SymmetricEncryptionKey = null;
            SymmetricDecryptionKey = null;
            Account = null;
        }
    }
}
