using MemoQServicesClient.TMService;
using MemoQServicesClient.TasksService;
using System;
using System.Threading;

namespace MemoQServicesClient
{
    internal class TMServiceTest
    {
        public void RepairTM(int tmPosition)
        {
            Log.WriteMajorSeparatorLine();
            Log.WriteLine("Repairing TM #" + ((int)(tmPosition + 1)).ToString() + ":");
            TMServiceClient tmServiceProxy = new TMServiceClient();
            TMInfo[] tmInfos = tmServiceProxy.ListTMs(null, null);
            if (tmPosition >= tmInfos.Length)
            {
                Log.WriteLine("Error. No TM exist in the list at this position.");
                Log.WriteMajorSeparatorLine();
                return;
            }

            Log.WriteLine($"TM Name: {tmInfos[tmPosition].Name}");

            TaskInfo taskInfo = tmServiceProxy.StartTMRepair(tmInfos[tmPosition].Guid);
            if (taskInfo.Status == TasksService.TaskStatus.InvalidTask ||
                taskInfo.Status == TasksService.TaskStatus.Cancelled ||
                taskInfo.Status == TasksService.TaskStatus.Failed)
            {
                Log.WriteLine($"Error. Invalid task status at starting the task: {taskInfo.Status}.");
                Log.WriteMajorSeparatorLine();
                return;
            }
            if (taskInfo.Status == TasksService.TaskStatus.Completed)
            {
                Log.WriteLine("TM Repair task completed before querying for status.");
                Log.WriteMajorSeparatorLine();
                return;
            }

            WaitExecutionFinished(taskInfo.TaskId, new TimeSpan(0, 10, 0));
        }
        private static void WaitExecutionFinished(Guid taskId, TimeSpan timeout)
        {
            var maxEndTime = DateTime.Now + timeout;
            var isTimedOut = false;

            TasksServiceClient taskServiceProxy = new TasksServiceClient();
            TaskInfo taskInfo;
            do
            {
                taskInfo = taskServiceProxy.GetTaskStatus(taskId);
                var now = DateTime.Now;
                Log.WriteLine($"Task Status at {now: HH:mm:ss.fff}: {taskInfo.Status}.");

                isTimedOut = now > maxEndTime;
                Thread.Sleep(500);
            }
            while ((taskInfo.Status == TasksService.TaskStatus.Pending || taskInfo.Status == TasksService.TaskStatus.Executing) &&
                   !isTimedOut);
            if (isTimedOut)
                Log.WriteLine("Task timed out.");
            Log.WriteMajorSeparatorLine();
        }

    }
}
