unit Api.ServiceImpl;

interface

uses
  XData.Server.Module, System.Generics.Collections,
  XData.Service.Common,
  Api.Service, Api.Database;

type
  [ServiceImplementation]
  TApiService = class(TInterfacedObject, IApiService)
  private
  ApiDB: TApiDatabase;
  public
  procedure AfterConstruction; override;
  procedure BeforeDestruction; override;
  function GetProjectTasks(projectId: string): TTasksList;

  end;

implementation

procedure TApiService.AfterConstruction;
begin
  inherited;
  ApiDB := TApiDatabase.Create(nil);
end;


procedure TApiService.BeforeDestruction;
begin
  ApiDB.Free;
  inherited;
end;


function TApiService.GetProjectTasks(projectId: string): TTasksList;
var
  taskMap: TDictionary<string, TTask>;
  task: TTask;
  item: TTaskItem;
  taskId: string;
begin
  Result := TTasksList.Create;
  TXDataOperationContext.Current.Handler.ManagedObjects.Add(Result);

  taskMap := TDictionary<string, TTask>.Create;
  try
    ApiDB.uqProjectTasks.Close;
    ApiDB.uqProjectTasks.ParamByName('PROJECT_ID').AsString := projectId;
    ApiDB.uqProjectTasks.Open;

    while not ApiDB.uqProjectTasks.Eof do
    begin
      taskId := ApiDB.uqProjectTasksTASK_ID.AsString;

      if not taskMap.TryGetValue(taskId, task) then
      begin
        task := TTask.Create;
        TXDataOperationContext.Current.Handler.ManagedObjects.Add(task);

        task.taskId := taskId;
        task.projectId := ApiDB.uqProjectTasksPROJECT_ID.AsString;

        taskMap.Add(taskId, task);
        Result.data.Add(task);
      end;

      item := TTaskItem.Create;
      TXDataOperationContext.Current.Handler.ManagedObjects.Add(item);

      item.taskItemId := ApiDB.uqProjectTasksTASK_ITEM_ID.AsString;
      item.taskId := ApiDB.uqProjectTasksTASK_ID.AsString;
      item.projectId := ApiDB.uqProjectTasksPROJECT_ID.AsString;

      item.application := ApiDB.uqProjectTasksAPPLICATION.AsString;
      item.version := ApiDB.uqProjectTasksAPP_VERSION.AsString;

      if ApiDB.uqProjectTasksTASK_DATE.IsNull then
        item.taskDate := 0
      else
        item.taskDate := ApiDB.uqProjectTasksTASK_DATE.AsDateTime;

      item.reportedBy := ApiDB.uqProjectTasksREPORTED_BY.AsString;
      item.assignedTo := ApiDB.uqProjectTasksASSIGNED_TO.AsString;

      item.status := ApiDB.uqProjectTasksSTATUS.AsString;

      if ApiDB.uqProjectTasksSTATUS_DATE.IsNull then
        item.statusDate := 0
      else
        item.statusDate := ApiDB.uqProjectTasksSTATUS_DATE.AsDateTime;

      item.fixedVersion := ApiDB.uqProjectTasksFIXED_VERSION.AsString;
      item.formSection := ApiDB.uqProjectTasksFORM_SECTION.AsString;
      item.issue := ApiDB.uqProjectTasksISSUE.AsString;
      item.notes := ApiDB.uqProjectTasksNOTES.AsString;

      task.items.Add(item);

      ApiDB.uqProjectTasks.Next;
    end;

    Result.count := Result.data.Count;
  finally
    taskMap.Free;
  end;
end;




initialization
  RegisterServiceType(TApiService);

end.
