using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;

namespace SamaPager_Server
{
    internal class Server
    {
        internal IPAddress ListeningIp { get; set; }
        internal int Port { get; set; }
        internal UdpClient UdpServer { get; set; }
        internal IPEndPoint ServerEndPoint { get; set; }

        internal Server(IPAddress listeningIP, int port)
        {
            this.ListeningIp = listeningIP;
            this.Port = port;
        }

        internal string StartServer()
        {
            ServerEndPoint = new IPEndPoint(this.ListeningIp, this.Port);
            try
            {
                this.UdpServer = new UdpClient(ServerEndPoint);
                return $"Listening on {ServerEndPoint}";
            }
            catch(Exception ex)
            {
                return $"Error ({ex.Message})";
            }
        }

        internal string StartListening()
        {
            IPEndPoint receiveEndPoint = ServerEndPoint;
            byte[] receivedBytes = UdpServer.Receive(ref receiveEndPoint);
            string receivedMessage = Encoding.UTF8.GetString(receivedBytes);
            return $"[{DateTime.Now}] {receiveEndPoint}: {receivedMessage}";
        }

        internal void KillServer()
        {
            this.UdpServer.Close();
        }
    }
}
