using MaxCommunication.DataBase.Document;
using System;
using System.Web.Http;
using System.Web.Http.Cors;
using System.Web.Http.SelfHost;

namespace ProjectManagementSystem.WebApi.Service
{
    public class WebApiServerHost
    {
        public TextDocument textDocument { get; set; } = new TextDocument(@"PMS\Log", "WebApiErrorLog_");

        public WebApiServerHost(bool IsListenterWebApi)
        {
            if (IsListenterWebApi) { StartServer(); }
        }

        private void StartServer()
        {
            try
            {
                HttpSelfHostConfiguration httpSelfHostConfiguration = new HttpSelfHostConfiguration("http://localhost:63300");
                httpSelfHostConfiguration.Formatters.Remove(httpSelfHostConfiguration.Formatters.XmlFormatter);
                httpSelfHostConfiguration.Formatters.Add(httpSelfHostConfiguration.Formatters.JsonFormatter);

                httpSelfHostConfiguration.Routes.MapHttpRoute(
                    name: "DefaultApi",
                    routeTemplate: "api/{controller}/{action}/{id}",
                    defaults: new { id = RouteParameter.Optional }
                );

                EnableCorsAttribute enableCorsAttribute = new EnableCorsAttribute("*", "*", "*");
                httpSelfHostConfiguration.EnableCors(enableCorsAttribute);

                HttpSelfHostServer httpSelfHostServer = new HttpSelfHostServer(httpSelfHostConfiguration);
                httpSelfHostServer.OpenAsync().Wait();
            }
            catch (Exception ex)
            {
                textDocument.WriteFile(ex.Message + "\n" + ex.StackTrace);
            }
        }
    }
}
