using System;
using System.Collections.Generic;
using System.Net;
using System.Text.RegularExpressions;

namespace Kernel
{
    public class Analyst
    {
        private List<Source> Sources = new List<Source>();

        public void AddSource(Source source)
        {
            Regex regex = new Regex(@"(http|https):\/\/[\w\-_]+(\.[\w\-_]+)+([\w\-\.,@?^=%&amp;:/~\+#]*[\w\-\@?^=%&amp;/~\+#])?");
            string address = source.Address;
            if(regex.IsMatch(address))
                if(address.EndsWith(".asmx")||address.EndsWith(".svc"))
                    Sources.Add(source);
        }

        public Dictionary<Source,SourceHistory> GetReport()
        {
            Dictionary<Source, SourceHistory> result = new Dictionary<Source, SourceHistory>();
            Exception exception = null;

            foreach (Source source in Sources)
            {
                exception = Poke(source.Address);
                SourceHistory history = new SourceHistory
                                            {
                                                ServiceId=source.SourceId,
                                                CheckDate=DateTime.Now,
                                                CurrentServiceState = exception!=null?ServiceState.Dead:ServiceState.Live,
                                                Exception=exception,
                                                Source = source,
                                                SourceHistoryId = Guid.NewGuid()
                                            };
                result.Add(source,history);
            }

            return result;
        }

        private Exception Poke(string serviceAddress)
        {
            Exception result = null;

            HttpWebRequest request = null;
            HttpWebResponse response = null;

            try
            {
                request = (HttpWebRequest) WebRequest.Create(serviceAddress);
                request.Timeout = 2000;
                response = (HttpWebResponse) request.GetResponse();
            }
            catch (Exception exception)
            {
                result = exception;
            }
            finally
            {
                if(response!=null)
                    response.Close();
            }

            return result;
        }

        public void WriteToRepository()
        {
            throw new NotImplementedException();
        }
    }
}
