/**
 * This file is part of the Meeds project (https://meeds.io/).
 * 
 * Copyright (C) 2022 Meeds Association contact@meeds.io
 * 
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 3 of the License, or (at your option) any later version.
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 * 
 * You should have received a copy of the GNU Lesser General Public License
 * along with this program; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
 */
package io.meeds.tenant.provisioning.listener;

import java.util.concurrent.CompletableFuture;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import org.exoplatform.services.listener.Event;
import org.exoplatform.services.listener.Listener;
import org.exoplatform.task.dto.TaskDto;
import org.exoplatform.task.service.TaskPayload;
import org.exoplatform.task.service.TaskService;

import io.meeds.tenant.provisioning.service.TenantProvisioningService;

public class TenantTaskCompletedListener extends Listener<TaskService, TaskPayload> {
  private static final Logger       LOG = LoggerFactory.getLogger(TenantTaskCompletedListener.class);

  private TenantProvisioningService tenantProvisioningService;

  private ClassLoader               classLoader;

  public TenantTaskCompletedListener(TenantProvisioningService tenantProvisioningService, ClassLoader classLoader) {
    this.tenantProvisioningService = tenantProvisioningService;
    this.classLoader = classLoader;
  }

  @Override
  public void onEvent(Event<TaskService, TaskPayload> event) throws Exception {
    TaskPayload data = event.getData();

    final TaskDto oldTask = data.before();
    final TaskDto newTask = data.after();

    CompletableFuture.runAsync(() -> {
      ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();
      Thread.currentThread().setContextClassLoader(classLoader);
      boolean completeStatusChanged = oldTask != null && newTask != null && newTask.isCompleted() != oldTask.isCompleted();
      if (completeStatusChanged) {
        long taskId = newTask.getId();
        boolean completed = newTask.isCompleted();
        try {
          tenantProvisioningService.changeDeedTenantCompletedStatus(taskId, completed);
        } catch (Exception e) {
          LOG.warn("Error while broadcasting Task {} as completed={} for its deed", taskId, completed, e);
        } finally {
          Thread.currentThread().setContextClassLoader(contextClassLoader);
        }
      }
    });
  }

}
