using MegaRobo.Connections.Web;
using MegaRobo.Logger;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;

namespace MegaRobo.C00225155.ControlDevices
{
    public class HttpListenerProvider
    {
        public HttpListenerProvider(ILogger logger)
        {
            this._Logger = logger;
        }


        private ILogger _Logger;
        private readonly IDictionary<string, HttpListenerService> _sources = new ConcurrentDictionary<string, HttpListenerService>(StringComparer.CurrentCultureIgnoreCase);

        public HttpListenerService GetOrAdd(string name, IPEndPoint host)
        {
            return this._sources.TryGetValue(name, out HttpListenerService service) ? service : this.Create(name, host);
        }

        public HttpListenerService Create(string name, IPEndPoint host)
        {
            var service = new HttpListenerService();
            service.Start(host);
            if (this._sources.ContainsKey(name))
            {
                this._sources[name] = service;
            }
            else
            {
                this._sources.TryAdd(name, service);
            }
            this._Logger?.LogInformation($"已开启端口为[{host}]的Web请求监听");
            return service;
        }
    }
}
