using System;
using System.Collections.Generic;
using System.Configuration;
using LeafWeb.Core.Entities;
using LeafWeb.Core.Remote;

namespace LeafWeb.WebCms.Services.PiscalQueue
{
	/// <summary>
	/// Thin layer over PiscalClient to translate Core entities to Piscal objects
	/// </summary>
	public class PiscalService
	{
		private readonly IPiscalClient _piscalClient;
		private readonly string _notifyCompleteUrl;

		public PiscalService(IPiscalClient piscalClient)
		{
			_piscalClient = piscalClient;
			_notifyCompleteUrl = 
				ConfigurationManager.AppSettings["LeafWebUrl"] +
				ConfigurationManager.AppSettings["PiscalNotifyCompleteUrlPath"];
		}

		public PiscalService() : this(new PiscalSshClient(ConfigurationManager.ConnectionStrings["PiscalServer"].ConnectionString))
		{
		}

		public string ServiceDescription => "Host: " + _piscalClient.Host;

		public void Run(LeafInput leafInput)
		{
			var inputFile = new PiscalLeafInput(leafInput);

			if (!string.IsNullOrEmpty(_notifyCompleteUrl))
				inputFile.NotifyCompleteUrl = _notifyCompleteUrl;

			// NOTE: Assume that from this address we don't want to store it
			if (string.Equals(leafInput.Email, "james.kolpack@gmail.com", StringComparison.InvariantCultureIgnoreCase))
				inputFile.SuppressStorageCopy = true;
			_piscalClient.RunLeafInput(inputFile);
		}

		public PiscalStatus GetStatus(LeafInput leafInput)
		{
			var inputFile = new PiscalLeafInput(leafInput);
			return _piscalClient.GetLeafInputStatus(inputFile);
		}

		public IEnumerable<LeafOutputFile> RetrieveOutputFiles(LeafInput leafInput)
		{
			var input = new PiscalLeafInput(leafInput);
			var piscalLeafOutputFiles = _piscalClient.RetrieveLeafOutput(input);
			foreach (var file in piscalLeafOutputFiles)
			{
				var leafOutputFile = file.GetLeafOutputFile();
				leafOutputFile.LeafInput = leafInput;
				yield return leafOutputFile;
			}
		}
		
		public void Cleanup(LeafInput leafInput)
		{
			var input = new PiscalLeafInput(leafInput);
			_piscalClient.CleanupLeafProcess(input);
		}

		public void Kill(LeafInput leafInput)
		{
			var input = new PiscalLeafInput(leafInput);
			_piscalClient.KillLeafProcess(input);
		}
	}
}