/*
 * 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.scheduling.task;

import static io.meeds.deeds.constant.CommonConstants.DEED_OWNERSHIP_TRANSFERRED_BLOCKCHAIN_EVENT;

import java.util.Set;
import java.util.concurrent.TimeUnit;

import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import org.exoplatform.commons.api.settings.SettingService;
import org.exoplatform.commons.api.settings.SettingValue;
import org.exoplatform.commons.api.settings.data.Context;
import org.exoplatform.commons.api.settings.data.Scope;
import org.exoplatform.container.ExoContainerContext;
import org.exoplatform.container.PortalContainer;

import io.meeds.deeds.constant.CommonConstants.DeedOwnershipTransferEvent;
import io.meeds.deeds.service.BlockchainService;
import io.meeds.deeds.service.ListenerService;

@Component
public class DeedOwnershipBlockchainMinedEventsCheckTask {

  private static final String  SETTING_LAST_TIME_CHECK_KEY = "minedDeedOwnershipsTransactionsCheck";

  private static final Scope   SETTING_SCOPE               = Scope.APPLICATION.id("DEED_TENANT_PROVISIONING");

  private static final Context SETTING_CONTEXT             = Context.GLOBAL.id("DEED_TENANT_PROVISIONING");

  @Autowired
  private ListenerService      listenerService;

  @Autowired
  private BlockchainService    blockchainService;

  private SettingService       settingService;

  @Scheduled(fixedDelay = 5, timeUnit = TimeUnit.MINUTES, initialDelay = 3)
  public synchronized void checkTransferredDeeds() {
    long lastBlock = blockchainService.getLastBlock();
    long lastCheckedBlock = getLastCheckedBlock();
    if (lastCheckedBlock == 0) {
      // If this is the first time that it's started, save the last block as
      // last checked one
      saveLastCheckedBlock(lastBlock);
      return;
    }
    Set<DeedOwnershipTransferEvent> events = blockchainService.getMinedTransferOwnershipDeedTransactions(lastCheckedBlock,
                                                                                                         lastBlock);
    if (!CollectionUtils.isEmpty(events)) {
      events.forEach(event -> listenerService.publishEvent(DEED_OWNERSHIP_TRANSFERRED_BLOCKCHAIN_EVENT,
                                                           event));
    }
    saveLastCheckedBlock(lastBlock);
  }

  private long getLastCheckedBlock() {
    ExoContainerContext.setCurrentContainer(PortalContainer.getInstance());
    try {
      long lastCheckedBlock = 0;
      SettingValue<?> settingValue = getSettingService().get(SETTING_CONTEXT, SETTING_SCOPE, SETTING_LAST_TIME_CHECK_KEY);
      if (settingValue != null && settingValue.getValue() != null) {
        lastCheckedBlock = Long.parseLong(settingValue.getValue().toString());
      }
      return lastCheckedBlock;
    } finally {
      ExoContainerContext.setCurrentContainer(null);
    }
  }

  private void saveLastCheckedBlock(long lastBlock) {
    ExoContainerContext.setCurrentContainer(PortalContainer.getInstance());
    try {
      getSettingService().set(SETTING_CONTEXT, SETTING_SCOPE, SETTING_LAST_TIME_CHECK_KEY, SettingValue.create(lastBlock));
    } finally {
      ExoContainerContext.setCurrentContainer(null);
    }
  }

  private SettingService getSettingService() {
    if (settingService == null) {
      settingService = PortalContainer.getInstance().getComponentInstanceOfType(SettingService.class);
    }
    return settingService;
  }

}
