﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;

namespace ForexRunner.Strategies
{
    public class OpsGenieHeartbeat : IEntryStrategy
    {
        private DateTime _nextHeartBeatTime = DateTime.Parse("2000-01-01");
        private readonly TimeSpan _duration;
        private string _name;

        public OpsGenieHeartbeat(TimeSpan duration, string name)
        {
            _duration = duration;
            _name = name;
        }

        public Frequency EntryFrequency
        {
            get { return Frequency.Second; }
        }

        public IEnumerable<PositionRequest> Evaluate(Tick currentTick, DateTime currentTime)
        {
            if (currentTime >= _nextHeartBeatTime)
            {
                ThreadPool.QueueUserWorkItem(state =>
                {
                    using (var client = new HttpClient())
                    {
                        var result = client.PostAsJsonAsync("https://api.opsgenie.com/v1/json/heartbeat/send", new
                        {
                            apiKey = ConfigurationManager.AppSettings["OpsGenie:APIKey"],
                            name = _name
                        }).Result;
                        //Console.WriteLine(result.Content.ReadAsStringAsync().Result);
                    }
                });
                _nextHeartBeatTime = DateTime.Now + _duration;
            }

            return null;
        }
    }
}
