﻿using System;
using System.Diagnostics;
using System.Net;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Owin.Hosting;
using Microsoft.WindowsAzure.ServiceRuntime;

namespace WorkerLogic
{
    public class CustomRoleEntryPoint : RoleEntryPoint
    {
        private IDisposable _app = null;
        private LoadClient loadClient = null;

        public override bool OnStart()
        {
            ServicePointManager.DefaultConnectionLimit = 12;

            // New code:
            var endpoint = RoleEnvironment.CurrentRoleInstance.InstanceEndpoints["http"];
            string baseUri = string.Format("{0}://{1}", endpoint.Protocol, endpoint.IPEndpoint);

            Trace.TraceInformation(String.Format("Starting OWIN at {0}", baseUri), "Information");

            _app = WebApp.Start<Startup>(new StartOptions(url: baseUri));

            this.loadClient = new LoadClient(
                connectionString: RoleEnvironment.GetConfigurationSettingValue("Microsoft.WindowsAzure.Plugins.Diagnostics.ConnectionString"),
                tableName: "currentloadtable",
                loadUrl: baseUri + "/api/load",
                deploymentId: RoleEnvironment.DeploymentId,
                roleInstanceId: RoleEnvironment.CurrentRoleInstance.Id,
                updateEvery: TimeSpan.FromSeconds(1));

            this.loadCheckTask = Task.Run(() => loadClient.Run(cts.Token), cts.Token);


            return base.OnStart();
        }

        CancellationTokenSource cts = new CancellationTokenSource();
        Task loadCheckTask = null;

        public override void Run()
        {
            while (true)
            {
                Thread.Sleep(TimeSpan.FromSeconds(10));
            }
        }

        public override void OnStop()
        {
            if (_app != null)
            {
                _app.Dispose();
            }

            cts.Cancel();

            base.OnStop();
        }
    }
}
