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

using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Net.NetworkInformation;

namespace Access_Control_Server
{
    class Comm
    {
        private static int remotePort = 45454;

        internal String SendToTerminal(String ip, String message)
        {
            Crypto crypto = new Crypto();

            IPAddress ipAddress = IPAddress.Parse(ip);
            Ping ping = new Ping();
            PingReply pingReply;

            TcpClient tcp = new TcpClient();
            Stream tcpStream;

            byte[] bytes;

            try
            {
                pingReply = ping.Send(ip, 100);
                if (pingReply.Status != IPStatus.Success) return "";
            }
            catch
            {
                return "";
            }

            message = DateTime.Now.ToString() + " " + message + '\0';

            tcp.Connect(new IPEndPoint(ipAddress, remotePort));
            tcpStream = tcp.GetStream();

            bytes = crypto.EncryptAES(message);
            tcpStream.Write(bytes, 0, bytes.Length);

            bytes = new byte[200];
            try
            {
                tcpStream.Read(bytes, 0, 200);
            }
            catch { };

            tcp.Close();

            return crypto.DecryptAES(bytes).Trim('\0');
        }
    }
}
