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

namespace RIMSI_Audio_multiplayer
{
    class SocketManager
    {

        private TcpClient tcpClient;

        private NetworkStream clientStream;
        private StreamWriter writer;


        private Thread readThread;

        //private String SocketIP = "192.168.0.157";
        private String SocketIP;
        private int SocketPort;
        private IPEndPoint serverEndPoint;

        private static SocketManager instance;

        public static SocketManager Instance
        {
            get
            {
                if (instance == null)
                {
                    instance = new SocketManager();
                }
                return instance;
            }
        }

        private SocketManager()
        { }

        public bool Connect(String _socketIP = "127.0.0.1", int _socketPort = 9999)
        {
            SocketIP = _socketIP;
            SocketPort = _socketPort;
            tcpClient = new TcpClient();
            serverEndPoint = new IPEndPoint(IPAddress.Parse(SocketIP), SocketPort);

            try
            {
                tcpClient.Connect(serverEndPoint);

            }
            catch (SocketException err)
            {
                Console.Write("Socket error: " + err);
                return false;
            }

            clientStream = tcpClient.GetStream();
            writer = new StreamWriter(clientStream);
            writer.AutoFlush = true;

            readThread = new Thread(ReadFromSocket);
            readThread.Start();

            return true;
        }

        public void WriteOnSocket(string msg)
        {
            if (writer != null)
            {
                try
                {
                    writer.WriteLine(msg);
                    Console.Write("written: " + msg);
                }
                catch (IOException ioe)
                {
                    Console.Write("unable to write on socket: " + ioe);
                }

            }

        }

        public void ReadFromSocket()
        {
            using (StreamReader reader = new StreamReader(tcpClient.GetStream(), Encoding.UTF8))
            {
                string line;
                 while ((line = reader.ReadLine()) != null)
                {                                                                      
                    // do something with line
                    Console.WriteLine(line);
                    GameStatus.Instance.ParseUpdateStatus(line);
                }
            }
        }
    }
}

    