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

namespace GatewayAPI
{
    public class GatewayServerAPI: IDisposable
    {
        public event GatewayServerStatusHandler StatusChange;

        private ServiceHost host;
        private string ipAddress = "localhost";
        private string port = "9080";
        private int maxClients = 24;
        private bool isAlive = false;
        private string pin;

        public bool IsAlive
        {
            get
            {
                return isAlive;
            }
        }
        public GatewayServerAPI()
        {
            this.Open();
        }
        public GatewayServerAPI(string pin)
        {
            this.pin = pin;
            this.Open();
        }
        public GatewayServerAPI(string pin, string ipAddress, string port)
        {
            this.pin = pin;
            this.ipAddress = ipAddress;
            this.port = port;
            this.Open();
        }
        public GatewayServerAPI(string pin, string ipAddress, string port, int maxClients)
        {
            this.pin = pin;
            this.ipAddress = ipAddress;
            this.port = port;
            this.maxClients = maxClients;
            this.Open();
        }
        ~GatewayServerAPI()
        {
            this.Close();
        }
        public void Dispose()
        {
            this.Close();
        }
        public void Open()
        {
            try
            {
                host = new ServiceHost(typeof(ServerControl));
                host.AddServiceEndpoint(typeof(IServerMethods), new NetTcpBinding(), "net.tcp://" + ipAddress + ":" + port + "/GatewayCommunication");
                ServiceThrottlingBehavior throttling = new ServiceThrottlingBehavior();
                throttling.MaxConcurrentSessions = maxClients;
                throttling.MaxConcurrentCalls = maxClients;
                host.Description.Behaviors.Add(throttling);
                host.Open();
                isAlive = true;
                if (StatusChange != null)
                    StatusChange(isAlive);
            }
            catch (Exception)
            {
                this.Close();
            }
                
        }
        public void Close()
        {
            isAlive = false;
            if (StatusChange != null)
                StatusChange(isAlive);
            host.Abort();
            host.Close();
        }
    }
}

