using System;
using System.Runtime.InteropServices;
using TaskSchedulerInterop;

namespace TaskScheduler
{
	[ComVisible(true)]
	public class ScheduledTasks : IDisposable
	{
		private ITaskScheduler its = null;

		internal static Guid ITaskGuid;

		internal static Guid CTaskGuid;

		public ScheduledTasks(string computer) : this()
		{
			this.its.SetTargetComputer(computer);
		}

		public ScheduledTasks()
		{
			CTaskScheduler cTaskScheduler = new CTaskScheduler();
			this.its = (ITaskScheduler)cTaskScheduler;
		}

		private string[] GrowStringArray(string[] s, uint n)
		{
			string[] array = new string[(long)s.Length + (long)((ulong)n)];
			for (int i = 0; i < s.Length; i++)
			{
				array[i] = s[i];
			}
			return array;
		}

		public string[] GetTaskNames()
		{
			string[] array = new string[0];
			int num = 0;
			IEnumWorkItems enumWorkItems;
			this.its.Enum(out enumWorkItems);
			IntPtr ptr;
			uint num2;
			while (enumWorkItems.Next(10u, out ptr, out num2) >= 0 && num2 > 0u)
			{
				array = this.GrowStringArray(array, num2);
				while (num2 > 0u)
				{
					IntPtr ptr2 = Marshal.ReadIntPtr(ptr, (int)((num2 -= 1u) * (uint)IntPtr.Size));
					array[num++] = Marshal.PtrToStringUni(ptr2);
					Marshal.FreeCoTaskMem(ptr2);
				}
				Marshal.FreeCoTaskMem(ptr);
			}
			return array;
		}

		public Task CreateTask(string name)
		{
			Task task = this.OpenTask(name);
			bool flag = task != null;
			if (flag)
			{
				task.Close();
				throw new ArgumentException("The task \"" + name + "\" already exists.");
			}
			Task result;
			try
			{
				object obj;
				this.its.NewWorkItem(name, ref ScheduledTasks.CTaskGuid, ref ScheduledTasks.ITaskGuid, out obj);
				ITask iTask = (ITask)obj;
				result = new Task(iTask, name);
			}
			catch
			{
				result = null;
			}
			return result;
		}

		public bool DeleteTask(string name)
		{
			bool result;
			try
			{
				this.its.Delete(name);
				result = true;
			}
			catch
			{
				result = false;
			}
			return result;
		}

		public Task OpenTask(string name)
		{
			Task result;
			try
			{
				object obj;
				this.its.Activate(name, ref ScheduledTasks.ITaskGuid, out obj);
				ITask iTask = (ITask)obj;
				result = new Task(iTask, name);
			}
			catch
			{
				result = null;
			}
			return result;
		}

		public void Dispose()
		{
			Marshal.ReleaseComObject(this.its);
			this.its = null;
		}

		static ScheduledTasks()
		{
			ScheduledTasks.ITaskGuid = Marshal.GenerateGuidForType(typeof(ITask));
			ScheduledTasks.CTaskGuid = Marshal.GenerateGuidForType(typeof(CTask));
		}
	}
}
