/*
 * This file is part of the Meeds project (https://meeds.io/).
 * Copyright (C) 2020 - 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;

import javax.annotation.PostConstruct;
import javax.servlet.ServletContext;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import org.exoplatform.container.PortalContainer;
import org.exoplatform.container.RootContainer.PortalContainerPostInitTask;
import org.exoplatform.services.listener.ListenerService;
import org.exoplatform.task.service.TaskService;

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

@Component
public class KernelIntegrationService {

  @Autowired
  private TenantProvisioningService tenantProvisioningService;

  @Autowired
  private ServletContext            servletContext;

  @PostConstruct
  public TenantTaskCompletedListener init() {
    TenantTaskCompletedListener taskSavedListener = new TenantTaskCompletedListener(tenantProvisioningService,
                                                                                    servletContext.getClassLoader());
    PortalContainer.addInitTask(servletContext, new PortalContainerPostInitTask() {
      @Override
      public void execute(ServletContext context, PortalContainer portalContainer) {
        ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();
        Thread.currentThread().setContextClassLoader(servletContext.getClassLoader());
        try {
          ListenerService listenerService = portalContainer.getComponentInstanceOfType(ListenerService.class);
          listenerService.addListener(TaskService.TASK_UPDATE, taskSavedListener);
        } finally {
          Thread.currentThread().setContextClassLoader(contextClassLoader);
        }
      }
    });
    return taskSavedListener;
  }

}
