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

namespace LeafWeb.Web.Services
{
	public class PiscalService
	{
		private readonly IPiscalClient _piscalClient;

		public PiscalService(IPiscalClient piscalClient)
		{
			_piscalClient = piscalClient;
		}

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

		public void Run(LeafInputFile leafInputFile)
		{
			var inputFile = new PiscalLeafInputFile(leafInputFile);
			_piscalClient.RunLeafInputFile(inputFile);
		}

		public PiscalStatus GetStatus(LeafInputFile leafInputFile)
		{
			var inputFile = new PiscalLeafInputFile(leafInputFile);
			return _piscalClient.GetLeafInputFileStatus(inputFile);
		}

		public IEnumerable<LeafOutputFile> RetrieveOutputFiles(LeafInputFile leafInputFile)
		{
			var inputFile = new PiscalLeafInputFile(leafInputFile);
			var piscalLeafOutputFiles = _piscalClient.RetrieveLeafOutput(inputFile);
			foreach (var file in piscalLeafOutputFiles)
			{
				var leafOutputFile = file.GetLeafOutputFile();
				leafOutputFile.LeafInputFile = leafInputFile;
				yield return leafOutputFile;
			}
		}

		public void Cleanup(LeafInputFile leafInputFile)
		{
			var inputFile = new PiscalLeafInputFile(leafInputFile);
			_piscalClient.CleanupLeafProcess(inputFile);
		}
	}
}