using System;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using InfluxDB.Client;

namespace Monithor.api {
	public class DbProxy {
		private static Influx _influx;
		public static  string LastUpdated;

		public static void Init() {
			var client = InfluxDBClientFactory.Create(Config.Url, Config.Token.ToCharArray());
			_influx = new Influx(client, Config.Org, Config.Bucket);
		}

		public static void ProcessMonitors(bool notify = true) {
			foreach (var monitor in Config.Monitors.FindAll(monitor => monitor.Update(monitor.GetFluxItems(_influx, "5m")))) {
				if (notify) {
					Config.Targets.FindAll(p => p.Monitor == monitor).ForEach(p => p.SendMessage());
				}
			}
		}

		[SuppressMessage("ReSharper", "FunctionNeverReturns")]
		public static Task BackgroundUpdate() {
			ProcessMonitors(false);
			while (true) {
				try {
					ProcessMonitors();
				}
				catch (Exception e) {
					Console.WriteLine(e);
				}

				LastUpdated = DateTime.Now.ToString("MMM dd yyyy, HH':'mm':'ss %K");
				Thread.Sleep(60000);
			}
		}
	}
}