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

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

import org.exoplatform.services.log.ExoLogger;
import org.exoplatform.services.log.Log;

import io.meeds.common.ContainerTransactional;
import io.meeds.tenant.hub.service.HubService;

/**
 * A Job that will frequently run when the Hub is connected to the WoM to update
 * the Hub Card
 */
@Component
public class HubPeriodicUpdateJob {

  private static final Log LOG         = ExoLogger.getLogger(HubPeriodicUpdateJob.class);

  @Autowired
  private HubService       hubService;

  private int              errorsCount = 0;

  @Scheduled(cron = "${meeds.deed.tenant.cron:0 0/2 * * * *}")
  @ContainerTransactional
  public void run() {
    try {
      hubService.updateHubCard();
    } catch (Exception e) {
      if (errorsCount == 0) {
        LOG.warn("Error while updating Hub Card", e);
      } else if (errorsCount < 10) {
        LOG.warn("Error while updating Hub Card: {}", e.getMessage());
      } else if (errorsCount == 10) {
        LOG.warn("Error while updating Hub Card (Log level will be switched to debug): {}", e.getMessage());
      } else {
        LOG.debug("Error while updating Hub Card: {}", e.getMessage());
      }
      errorsCount++;
    }
  }

}
