using HeuristicLab.Clients.Hive.WebJobManager.Services;
using HeuristicLab.Common;
using Microsoft.AspNet.SignalR;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
namespace HeuristicLab.Clients.Hive.WebJobManager
{
///
/// SignalR Hub for updating a current selected job
///
public class JobUpdaterHub : Hub
{
private RefreshableJob Job;//Current job (only used as reference, instance gets lost)
///
/// Initial connection call from client
///
public void initConnection()
{
FileOpeningService.Instance.previousids = new List();
FileOpeningService.Instance.previousLogs = new List();
Job = FileOpeningService.Instance.Job;
updateAll();//start initial update
}
///
/// Starts update loop for selected job. Sends end token when done and calls GC
///
public void updateAll()
{
FileOpeningService.Instance.refreshJob();//refresh all data from job
Job = FileOpeningService.Instance.Job;
updateJob();
foreach (var t in Job.HiveTasks)
{
looperTasks(t);//starts recursive loop
}
Clients.All.requestDone();//Final note from server when all tasks are checked.
//Client starts countdown and resends the updateAll when done
GC.Collect();
GC.WaitForPendingFinalizers();
}
public void updateJob()
{
Clients.All.processJobData(Job.Job.CalculatingCount, Job.Job.FinishedCount);
}
///
/// Recursive loop for updating the selected job view
///
/// Loops on all children
private void looperTasks(HiveTask task)
{
try
{
int index;
bool test = false;
if (FileOpeningService.Instance.previousids.Contains(task.Task.Id))
{
index = FileOpeningService.Instance.previousids.IndexOf(task.Task.Id);
}
else
{//initial add to previous list, used to check if updates happened
FileOpeningService.Instance.previousids.Add(task.Task.Id);
index = FileOpeningService.Instance.previousids.IndexOf(task.Task.Id);
FileOpeningService.Instance.previousLogs.Add(task.Task.StateLog.Count);
test = true;//initial added task, data must be sent
}
var previous = FileOpeningService.Instance.previousLogs[index];
if (test || previous < task.Task.StateLog.Count)
{//Checks if change happened so data is not sent unnecessary
FileOpeningService.Instance.previousLogs[index] = task.Task.StateLog.Count;
JsonSerializerSettings settings = new JsonSerializerSettings();
settings.ContractResolver = new JsonTaskResolver();
//limits loaded data
var json = JsonConvert.SerializeObject(task.Task, settings);
Clients.All.processData(task.Task.Id, json, task.ItemTask.Name.ToString());
//data sent to user
}
foreach (var t in task.ChildHiveTasks)
{//loop on childs
looperTasks(t);
}
}
catch (JsonSerializationException e) { }//Taskresolver fixes much but img tries to throw this sometimes
}
///
/// Restarts a failed task, sent by client
///
/// Task id from failed task
public void restartTask(Guid id)
{
((HiveServiceLocatorWeb)(HiveServiceLocatorWeb.Instance)).getHiveServiceClient().RestartTask(id);
}
}
}